public void OnReceiveUpload(string jsonText) { GeneSet genes = null; try { loadingSpinner.SetActive(true); var json = JSONObject.Parse(jsonText); var filename = json.GetString("filename"); var data = json.GetString("data"); Debug.Log("OnReceiveUpload filename: " + filename); Debug.Log("OnReceiveUpload data: " + data); genes = ParseGeneSet(data); DebugLogGeneSet(genes); } catch { loadingSpinner.SetActive(false); } StartCoroutine(GameObject.Find("ScriptHolder").GetComponent <Colour>().ColourByGeneSet(genes)); }
internal void SetFamily(Creature motherCreature, Creature fatherCreature, uint no) { mother = motherCreature; father = fatherCreature; Generation = (uint)Mathf.FloorToInt(Mathf.Max(motherCreature.Generation, fatherCreature.Generation)) + 1; childNo = no; birthTime = Time.time; genes = new GeneSet(motherCreature, fatherCreature); ReproductiveUrge = 0f; gender = (Random.Range(0, 2) == 1 ? GenderType.Male : GenderType.Female); if (gestation != null && gender == GenderType.Male) { gestation.enabled = false; } gestation.Reactivate(); birthTime = Time.time; name = ID; maxNutrition = Mathf.Clamp(Mathf.Lerp(originalMaxNutrition - 2, originalMaxNutrition + 2, ability[Genotype.Nutrition]), 1, Mathf.Infinity); maxHydration = Mathf.Clamp(Mathf.Lerp(originalMaxHydration - 2, originalMaxHydration + 2, ability[Genotype.Nutrition]), 1, Mathf.Infinity); Nutrition = maxNutrition; Hydration = maxHydration; }
void Mutate(Cell start, Cell destination, int k) { switch (mutationType) { case MutationType.None: { if (destination.Gene != start.Gene) { AssignGeneToTile(k, nextGenerationIndex, 0, Cell.CellStatus.Collision); } break; } case MutationType.Average: { int m = (start.Gene + destination.Gene) / 2; AssignGeneToTile(k, nextGenerationIndex, m, m == 0 ? Cell.CellStatus.Empty : Cell.CellStatus.Normal); break; } case MutationType.AverageWithRandom: { int a = (start.Gene + destination.Gene) / 2; int r = GeneSet.GetRandomGene(); int m = a * 4 + r; m /= 5; AssignGeneToTile(k, nextGenerationIndex, m, m == 0 ? Cell.CellStatus.Empty : Cell.CellStatus.Normal); break; } case MutationType.Random: { int m = GeneSet.GetRandomGene(); AssignGeneToTile(k, nextGenerationIndex, m, m == 0 ? Cell.CellStatus.Empty : Cell.CellStatus.Normal); break; } case MutationType.Barricelli: { if (cells[k, currentGenerationIndex].Status == Cell.CellStatus.Normal) { AssignGeneToTile(k, nextGenerationIndex, 0, Cell.CellStatus.Collision); } else { AssignGeneToTile(k, nextGenerationIndex, FindDistance(k), Cell.CellStatus.Normal); } break; } } }
public CreatureBirthDataPoint(string _sn, GeneSet _gns, uint _gen, uint _cno, ParentStats _fth, ParentStats _mth) { sn = _sn; gns = _gns; gen = _gen; cno = _cno; fth = _fth; mth = _mth; }
public CreatureBirthDataPoint(Creature creature) { sn = creature.name; gns = creature.genes; gen = creature.Generation; cno = creature.childNo; fth = new ParentStats(creature.father); mth = new ParentStats(creature.mother); }
public static GeneSet GetFirstGenerationGenes() { GeneSet fgg = new GeneSet(); foreach (string genotype in System.Enum.GetNames(typeof(Genotype))) { Genotype enumGenotype; System.Enum.TryParse(genotype, out enumGenotype); fgg.Add(enumGenotype, Random.Range(0.4f, 0.7f)); } fgg[Genotype.MutationChance] = Random.Range(0.01f, 0.1f); return(fgg); }
// Find the expression values corresponding with the entered gene, then start the colouring and similarity calculating processes public void ColourFromText(string geneName, bool panel = false) { SetMaxValue(); currentGene = geneName.Trim(); CurrentGeneSet = null; int geneIndex = FindIndexOfGene(geneName); // If the gene name was found, load that dataset into the pieces if (geneIndex > -1) { if (panel) { computeDistancesP(geneIndex); //baseGene = currentGene; } // Update current gene info gText.text = "Current gene: " + SentenceCase(geneName); SetGeneSetLabels("", ""); float lMax = -1; float lMin = 100; if (norm) { // Find the local min and max if in normalised mode for (int i = 0; i < 18; i++) { if (values[geneIndex].Values[i] > lMax) { lMax = values[geneIndex].Values[i]; } if (values[geneIndex].Values[i] < lMin) { lMin = values[geneIndex].Values[i]; } } } for (int i = 0; i < 18; i++) { colourHeartPiece(hp[i], values[geneIndex].Values[i], lMax, lMin); } } else { // Update current gene info gText.text = "Current gene: None"; resetColour(); //Debug.Log ("Gene with name " + geneName + " not found."); content.GetComponent <PanelScript>().sleep(); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jo = JObject.Load(reader); GeneSet importedSet = new GeneSet(); // new Dictionary<Genotype, float> foreach (KeyValuePair <string, JToken> entry in jo) { Genotype genotype; Enum.TryParse(entry.Key, out genotype); importedSet.Add(genotype, entry.Value.ToObject <float>()); } return(importedSet); }
public GeneSet ParseGeneSet(string text) { /* * Parse a list of gene names, one per line. Also detects and parses GSEA/MSigDB format * 'text', 'grp' and 'gmx' format (where the first two header lines are gene set name * and description) */ var geneset = new GeneSet(); string name = ""; string description = ""; List <string> genes = new List <string>(); // We also split on escaped endline sequences to deal with strings deserialized from JSON string[] lines = text.Split( new[] { "\r\n", "\r", "\n", "\\r\\n", "\\r", "\\n" }, System.StringSplitOptions.RemoveEmptyEntries); int count = 0; foreach (var line in lines) { count++; if (count == 2 && (line.Substring(0, 2) == "> " || line.Substring(0, 2) == "# ")) { name = genes[0]; genes.RemoveAt(0); description = line.Substring(2).Trim(); continue; } var geneName = line.Trim(); if (!string.IsNullOrEmpty(geneName)) { genes.Add(geneName); } } geneset.Name = name; geneset.Description = description; geneset.Genes = genes; return(geneset); }
void AssignGeneToTile(int x, int y, int gene, Cell.CellStatus status) { Debug.Assert(textures != null); Debug.Assert(cells != null); cells[x, y].Gene = Extensions.Clamp(gene, GeneSet.MinGene, GeneSet.MaxGene); cells[x, y].Status = status; int textureX = (x * GeneSet.width) / PNGSize; int textureY = (y * GeneSet.height) / PNGSize; int chunkX = (x * GeneSet.width) % PNGSize; int chunkY = (y * GeneSet.height) % PNGSize; Texture2D t; Rect r; switch (status) { case Cell.CellStatus.Normal: { t = GeneSet.GetSpriteFromGene(cells[x, y].Gene).texture; r = GeneSet.GetSpriteFromGene(cells[x, y].Gene).textureRect; break; } case Cell.CellStatus.Collision: { t = GeneSet.Collision.texture; r = GeneSet.Collision.textureRect; break; } default: { t = GeneSet.Empty.texture; r = GeneSet.Empty.textureRect; break; } } textures[textureX, textureY].SetPixels(chunkX, chunkY, GeneSet.width, GeneSet.height, t.GetPixels((int)r.x, (int)r.y, (int)r.width, (int)r.height)); }
// Reset everything to how it was at the start public void Reset() { cb = false; eyeButton.image.overrideSprite = null; colourButton.image.overrideSprite = null; IF.text = ""; resetColour(); gText.text = "Current gene: None"; currentGene = ""; CurrentGeneSet = null; //baseGene = ""; if (norm) { toggleNormalised(); } SetGeneSetLabels("", ""); SetMaxValue(); }
public GeneSet LoadPresetGeneSet(string resourceName) { GeneSet genes = null; try { loadingSpinner.SetActive(true); TextAsset textAsset = Resources.Load("genesets/" + resourceName) as TextAsset; genes = ParseGeneSet(textAsset.text); Resources.UnloadAsset(textAsset); DebugLogGeneSet(genes); } catch { loadingSpinner.SetActive(false); } return(genes); }
public void FromParentGenes(GeneSet motherGenes, GeneSet fatherGenes) { Clear(); foreach (string genotype in System.Enum.GetNames(typeof(Genotype))) { Genotype enumGenotype; System.Enum.TryParse(genotype, out enumGenotype); bool useFatherGenes = RandomBool; bool mutate = Random.Range(0, Mathf.Lerp(256, 1, (motherGenes[Genotype.MutationChance] + fatherGenes[Genotype.MutationChance]) / 2)) == 0; float geneValue = useFatherGenes ? fatherGenes[Genotype.MutationChance] : motherGenes[Genotype.MutationChance]; if (mutate) { geneValue += RandomBool ? geneValue : -geneValue; } Add(enumGenotype, Mathf.Clamp(geneValue, 0f, 1f)); } }
private void Awake() { transform.parent = GameObject.Find("Creatures").transform; originalScale = transform.localScale; navAgent = GetComponent <NavMeshAgent>(); gestation = GetComponent <GestationHandler>(); birthTime = Time.time; if (Generation == 1) { genes = GeneSet.GetFirstGenerationGenes(); birthTime = Time.time - 60f; maxNutrition = Mathf.Clamp(Mathf.Lerp(originalMaxNutrition - 2, originalMaxNutrition + 2, ability[Genotype.Nutrition]), 1, Mathf.Infinity); maxHydration = Mathf.Clamp(Mathf.Lerp(originalMaxHydration - 2, originalMaxHydration + 2, ability[Genotype.Nutrition]), 1, Mathf.Infinity); Nutrition = Random.Range(1f, maxNutrition); Hydration = Random.Range(1f, maxHydration); ReproductiveUrge = Random.Range(0.1f, 0.35f); } else { gender = (Random.Range(0, 2) == 1 ? GenderType.Male : GenderType.Female); } if (gestation != null && gender == GenderType.Male) { gestation.enabled = false; } ReproductiveUrge = 0f; CreatureDatabase.RegisterCreature(this); specieNo = (uint)CreatureDatabase.GetCreatureCount(this); name = ID; StartCoroutine(UpdateSight()); }
public void DebugLogGeneSet(GeneSet genes) { Debug.Log("Gene set name: " + genes.Name); Debug.Log("Gene set description: " + genes.Description); Debug.Log("Gene set genes: " + string.Join(", ", genes.Genes.ToArray())); }
public GeneSet(GeneSet motherGenes, GeneSet fatherGenes) { FromParentGenes(motherGenes, fatherGenes); }
// Find the expression values corresponding with the entered gene, then start the colouring and similarity calculating processes public void ColourFromText(string geneName, bool panel = false) { SetMaxValue(); currentGene = geneName.Trim(); string copyGene = geneCopyField.text; CurrentGeneSet = null; int geneIndex = FindIndexOfGene(geneName); int copyGeneIndex = FindIndexOfGene(copyGene.Trim()); // If the gene name was found, load that dataset into the pieces if (geneIndex > -1) { if (panel) { computeDistancesP(geneIndex); //baseGene = currentGene; } // Update current gene info gText.text = "Current gene: " + SentenceCase(geneName); SetGeneSetLabels("", ""); float lMax = -1; float lMin = 100; if (norm) { // Find the local min and max if in normalised mode for (int i = 0; i < 18; i++) { if (values[geneIndex].Values[i] > lMax) { lMax = values[geneIndex].Values[i]; } if (values[geneIndex].Values[i] < lMin) { lMin = values[geneIndex].Values[i]; } } } for (int i = 0; i < 18; i++) { colourHeartPiece(hp[i], values[geneIndex].Values[i], lMax, lMin); safeOriginal(values[geneIndex].Values[i], lMax, lMin); geneOriginalText.text = "Currently selected gene for main model: " + SentenceCase(geneName); mainGene = SentenceCase(geneName); } logFile.writeToFile(SentenceCase(geneName), false); } if (copyGeneIndex > -1) { if (panel) { computeDistancesP(copyGeneIndex); //baseGene = currentGene; } float lMax = -1; float lMin = 100; if (norm) { // Find the local min and max if in normalised mode for (int i = 0; i < 18; i++) { if (values[copyGeneIndex].Values[i] > lMax) { lMax = values[copyGeneIndex].Values[i]; } if (values[copyGeneIndex].Values[i] < lMin) { lMin = values[copyGeneIndex].Values[i]; } } } for (int i = 0; i < 18; i++) { colourHeartPiece(copyhp[i], values[copyGeneIndex].Values[i], lMax, lMin); safeCopy(values[copyGeneIndex].Values[i], lMax, lMin); geneCopyText.text = "Currently selected gene for second model: " + SentenceCase(copyGene); secondGene = SentenceCase(copyGene); } logFile.writeToFile(SentenceCase(copyGene), true); } else { // Update current gene info gText.text = "Current gene: None"; resetColour(); //Debug.Log ("Gene with name " + geneName + " not found."); content.GetComponent <PanelScript>().sleep(); } }
void Initialize() { GeneSetIndex = geneSetIndex; rowStates = new Random.State[height]; geneBrushIndex = 0; UpdateGeneBrushPreview(); if (useSeed) { Random.InitState(seed); } else { seed = (int)System.DateTime.Now.Ticks; Random.InitState(seed); } { Debug.Assert(currentSeedText != null); Text t = currentSeedText.GetComponent <Text>(); Debug.Assert(t != null); t.text = "Seed: " + seed; } foreach (Transform child in transform) { GameObject.Destroy(child.gameObject); } Debug.Assert(GeneSet != null); textureDimensionX = width * GeneSet.width / PNGSize; if ((width * GeneSet.width) % PNGSize > 0) { ++textureDimensionX; } textureDimensionY = height * GeneSet.height / PNGSize; if ((height * GeneSet.height) % PNGSize > 0) { ++textureDimensionY; } textures = new Texture2D[textureDimensionX, textureDimensionY]; chunks = new GameObject[textureDimensionX, textureDimensionY]; for (int i = 0; i < textureDimensionX; ++i) { for (int j = 0; j < textureDimensionY; ++j) { textures[i, j] = new Texture2D( Mathf.Min(width * GeneSet.width, PNGSize), Mathf.Min(height * GeneSet.height, PNGSize)); Debug.Assert(textures[i, j] != null); textures[i, j].filterMode = FilterMode.Point; Sprite sprite = Sprite.Create( textures[i, j], new Rect(0, 0, textures[i, j].width, textures[i, j].height), new Vector2(0f, 0f), 1); Debug.Assert(sprite != null); chunks[i, j] = GameObject.Instantiate(chunkPrefab); Debug.Assert(chunks[i, j] != null); chunks[i, j].transform.position = new Vector3(i * PNGSize, j * PNGSize); chunks[i, j].transform.parent = transform; SpriteRenderer sr = chunks[i, j].GetComponent <SpriteRenderer>(); Debug.Assert(sr != null); sr.sprite = sprite; } } GeneSet.ResetMapping(); if (shuffleTileMapping) { Random.State tempState = Random.state; GeneSet.ShuffleMapping(); Random.state = tempState; } cells = new Cell[width, height]; currentGenerationIndex = 0; nextGenerationIndex = currentGenerationIndex + 1; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { if (populate && y == currentGenerationIndex) { int randomGene = GeneSet.GetRandomGene(); AssignGeneToTile(x, y, randomGene, randomGene == 0 ? Cell.CellStatus.Empty : Cell.CellStatus.Normal); } else { AssignGeneToTile(x, y, 0, Cell.CellStatus.Empty); } } } foreach (Texture2D t in textures) { t.Apply(); } }
public IEnumerator ColourByGeneSet(GeneSet geneset) { yield return(new WaitForSeconds(5f)); int yield_every = 10; float yield_time = 0.05f; //loadingSpinner.SetActive(true); // allGeneNames gets populated on startup - we can't do anything until it's filled while (!_allGenes_ready) { yield return(new WaitForSeconds(0.2f)); } var _normalizePerGene = true; //Debug.Log(geneset.Genes.Count); // ResetAll(); currentGene = ""; CurrentGeneSet = geneset; // valid genes in the uploaded gene set which are absent in the expression data var missingGenes = new List <string>(); var averageValues = new float[18]; int count = 0; foreach (string geneName in geneset.Genes) { count++; var geneNameLower = geneName.ToLower(); if (!expressionDataNameIndexMapping.ContainsKey(geneNameLower)) { // Debug.Log("WARNING: Gene name " + geneName + " not found in expression dataset."); missingGenes.Add(geneName); #if UNITY_WEBGL //JsAlert(geneName + " is not a valid gene name."); #endif //return; if (count % yield_every == 0) { yield return(new WaitForSeconds(yield_time)); } continue; } if (!allGeneNames.Contains(geneNameLower)) { Debug.LogError("ERROR: Gene '" + geneName + "' is not a valid mouse gene name."); JsAlert(geneName + " is not a valid MGI mouse gene symbol (GRCm38, MGI vM9). " + "Maybe you need to convert your gene identifiers at http://www.informatics.jax.org/batch ?"); //loadingSpinner.SetActive(false); //return; yield break; } var geneIndex = expressionDataNameIndexMapping[geneNameLower]; // var geneIndex = FindIndexOfGene(geneName); var expressionForGene = values[geneIndex].Values.ToArray(); if (_normalizePerGene) { expressionForGene = NormalizeFloatArray(expressionForGene); } #if UNITY_EDITOR //Debug.Log("geneName, geneIndex: " + geneName + ", " + geneIndex); #endif #if UNITY_EDITOR for (int i = 0; i < 18; i++) { // Debug.Log("Gene: " + geneName + ", Piece " + i.ToString() + ", Value: " + expressionForGene[i].ToString()); } #endif // sum for (int i = 0; i < 18; i++) { averageValues[i] += expressionForGene[i]; } if (count % yield_every == 0) { yield return(new WaitForSeconds(yield_time)); } } if (missingGenes.Count > 0) { var _warningMsg = "WARNING: Some genes in the geneset are valid mouse genes but are absent from the expression dataset: " + string.Join(", ", missingGenes); Debug.Log(_warningMsg); JsAlert(_warningMsg); } // divide by number of genes in the set to obtain the average for (int i = 0; i < 18; i++) { averageValues[i] /= geneset.Genes.Count; } yield return(null); #if UNITY_EDITOR for (int i = 0; i < 18; i++) { Debug.Log("Piece " + i.ToString() + " average: " + averageValues[i].ToString()); } Debug.Log("Min: " + averageValues.Min().ToString()); Debug.Log("Max: " + averageValues.Max().ToString()); yield return(null); #endif // apply average colours to model maxValue = averageValues.Max(); var minValue = averageValues.Min(); // norm = true; for (int i = 0; i < 18; i++) { colourHeartPiece(hp[i], averageValues[i], maxValue, minValue); yield return(null); } SetGeneSetLabels(geneset.Name, geneset.Description); //loadingSpinner.SetActive(false); }
// TODO: Consider making this a coroutine so we can show a loading spinner // for larger gene sets. public void ColourByGeneSet(GeneSet geneset) { var _normalizePerGene = true; // ResetAll(); currentGene = ""; CurrentGeneSet = geneset; var averageValues = new float[18]; foreach (string geneName in geneset.Genes) { var geneIndex = FindIndexOfGene(geneName); var expressionForGene = values[geneIndex].Values.ToArray(); if (_normalizePerGene) { expressionForGene = NormalizeFloatArray(expressionForGene); } #if UNITY_EDITOR Debug.Log("geneName, geneIndex: " + geneName + ", " + geneIndex); #endif if (geneIndex == -1) { Debug.LogError(geneName + " not found."); #if UNITY_WEBGL JsAlert(geneName + " is not a valid gene name."); #endif return; } #if UNITY_EDITOR for (int i = 0; i < 18; i++) { Debug.Log("Gene: " + geneName + ", Piece " + i.ToString() + ", Value: " + expressionForGene[i].ToString()); } #endif // sum for (int i = 0; i < 18; i++) { averageValues[i] += expressionForGene[i]; } } // divide by number of genes in the set to obtain the average for (int i = 0; i < 18; i++) { averageValues[i] /= geneset.Genes.Count; } #if UNITY_EDITOR for (int i = 0; i < 18; i++) { Debug.Log("Piece " + i.ToString() + " average: " + averageValues[i].ToString()); } Debug.Log("Min: " + averageValues.Min().ToString()); Debug.Log("Max: " + averageValues.Max().ToString()); #endif // apply average colours to model maxValue = averageValues.Max(); var minValue = averageValues.Min(); // norm = true; for (int i = 0; i < 18; i++) { colourHeartPiece(hp[i], averageValues[i], maxValue, minValue); } SetGeneSetLabels(geneset.Name, geneset.Description); }