/// <summary> /// Constructor /// </summary> /// <param name="agents">the agents</param> /// <param name="species">the species</param> /// <param name="generation">the generation</param> public GenerationEvaluator(List <AgentObject> agents, List <Species> species, int generation) { _generation = generation; _amountSpecies = species.Count; _bestAgent = GetBestAgent(agents); _averageFitness = CalculateAverageFitness(agents); }
public bool CanAgentSolveXOR(AgentObject agent) { double result1 = agent.Genome.Calculate(new double[] { 0, 0, 1 })[0]; double result2 = agent.Genome.Calculate(new double[] { 0, 1, 1 })[0]; double result3 = agent.Genome.Calculate(new double[] { 1, 0, 1 })[0]; double result4 = agent.Genome.Calculate(new double[] { 1, 1, 1 })[0]; if (result1 > 0.5) { return(false); } if (result2 < 0.5) { return(false); } if (result3 < 0.5) { return(false); } if (result4 > 0.5) { return(false); } return(true); }
public void AllAgentsKilledCallback(List <AgentObject> agents, List <Species> species, int generation) { //Destry all player foreach (GameObject gameObject in GameObject.FindGameObjectsWithTag("Player")) { Destroy(gameObject); } GenerationEvaluator eval = new GenerationEvaluator(agents, species, generation); AgentObject bestAgent = eval.BestAgent; Debug.Log("All agents dead. Best fitness: " + bestAgent.GetFitness() + ", Average: " + eval.AverageFitness); //GUI Values _bestFitnessLastGeneration = bestAgent.GetFitness(); _averageFitnessLastGeneration = eval.AverageFitness; if (_bestTotalFitness < _bestFitnessLastGeneration) { _bestTotalFitness = _bestFitnessLastGeneration; } if (_bestAverageFitness < _averageFitnessLastGeneration) { _bestAverageFitness = _averageFitnessLastGeneration; } //Start next generation if the evaluation is running if (_evaluationRunning) { _manager.GenerateNextGeneration(); } }
/// <summary> /// Createa new agent with a new genome that is created by crossover of the two parents /// </summary> /// <param name="moreFitParent">the more fit parent</param> /// <param name="lessFitParent">the less fit parent</param> /// <returns>the newly created agent</returns> public AgentObject CrossOverAgent(AgentObject moreFitParent, AgentObject lessFitParent) { Genome childGenome = Genome.CrossOver(moreFitParent.Genome, lessFitParent.Genome); AgentObject child = _callback.InitNewAgent(this, childGenome); return(child); }
public void CreateInitialPopulation(Genome startingGenome, GeneCounter nodeInnovationCounter, GeneCounter connectionInnovationCounter, int populationSize, bool randomizeWeights) { _generation = 0; _nodeInnovationCounter = nodeInnovationCounter; _connectionInnovationCounter = connectionInnovationCounter; _populationSize = populationSize; _mutationLog = new MutationLog(); _agents = new List <AgentObject>(); _species = new List <Species>(); for (int i = 0; i < _populationSize; i++) { Genome randomGenome = new Genome(startingGenome); if (randomizeWeights) { foreach (ConnectionGene con in randomGenome.Connections.Values) { con.Weight = Random.Range(-1f, 1f); } } AgentObject agent = _callback.InitNewAgent(this, randomGenome); _agents.Add(agent); } PlaceAgentInSpecies(_agents, _species); //Notify the callback if not existing if (_callback != null) { _callback.AgentsInitializedCallback(_agents, _species, _generation); } }
/// <summary> /// Select a new random representive agent /// </summary> public void SelectNewRandomRepresentiveAgent() { if (_members.Count == 0) { throw new System.Exception("No Members in Species. Can't select a new Representive Agent"); } int index = Random.Range(0, _members.Count); _representiveAgent = _members[index]; }
private AgentObject GetBestAgent(List <AgentObject> agents) { AgentObject best = null; foreach (AgentObject agent in agents) { if (best == null || best.GetFitness() < agent.GetFitness()) { best = agent; } } return(best); }
public void SetUp() { populationManager = new PopulationManager(); agent1 = new CustomAgent(populationManager, new Genome(), 1); agent2 = new CustomAgent(populationManager, new Genome(), 2); agent3 = new CustomAgent(populationManager, new Genome(), 4); species = new Species(0, agent1); species.Members.Add(agent1); species.Members.Add(agent2); species.Members.Add(agent3); }
/// <summary> /// Check if a species is for the given agent available /// </summary> /// <param name="agent">The agent that should be checked</param> /// <param name="species">List of species that will be checked</param> /// <returns>The first matching species or null if no species was found</returns> public Species IsSpeciesAvailableForAgent(AgentObject agent, List <Species> species) { foreach (Species s in species) { float distanceValue = Genome.CompabilityDistanceFunction(s.RepresentiveAgent.Genome, agent.Genome, _FACTOR_EXCESS_GENES, _FACTOR_DISJOINT_GENES, _FACTOR_AVG_WEIGHT_DIF, _THRESHOLD_NUMBER_OF_GENES); if (distanceValue <= _COMPABILITY_THRESHOLD) { //Species found return(s); } } return(null); }
public void AllAgentsKilledCallback(List <AgentObject> agents, List <Species> species, int generation) { //Destry all player foreach (GameObject gameObject in GameObject.FindGameObjectsWithTag("Player")) { Destroy(gameObject); } GenerationEvaluator eval = new GenerationEvaluator(agents, species, generation); AgentObject bestAgent = eval.BestAgent; Debug.Log("All agents dead. Best fitness: " + bestAgent.GetFitness() + ", Average: " + eval.AverageFitness); //Fill the screen FillXorScreen(bestAgent.Genome, _screen, _screenObjPrefab); SetDisplay(bestAgent.Genome); if (CanAgentSolveXOR(bestAgent) || eval.Generation > 500) { foreach (NodeGene node in bestAgent.Genome.Nodes.Values) { Debug.Log("Node: " + node.ID + ", Type: " + node.Type); } foreach (ConnectionGene connection in bestAgent.Genome.Connections.Values) { if (connection.Expressed) { Debug.Log("Connection: In: " + connection.InNode + " Out: " + connection.OutNode + ", Weight: " + connection.Weight + ", InnovationNumber: " + connection.InnovationNumber); } } result.Add(eval.Generation); if (result.Count < amountRuns) { _manager.CreateInitialPopulation(startingGenome, new GeneCounter(6), new GeneCounter(9), 400); } else { Debug.Log("FINIIIISHED"); } } else { _manager.GenerateNextGeneration(); } }
/// <summary> /// Called when an agent dies. The Manager will check if there are active agents left. /// The AgentKilled() method in the IPopulationManagerCallback will be called, and the llAgentsKilledCallback() method /// </summary> public void AgentKilled(AgentObject killedAgent) { //Notify the callback _callback.AgentKilledCallback(killedAgent); //Check for remaining agents foreach (AgentObject agent in _agents) { //Break if (agent.Active) { return; } } _callback.AllAgentsKilledCallback(_agents, _species, _generation); }
public static UrbAgent LoadAgentFromID(int ID, UrbTile Tile, UrbObjectData Data) { if (ID < 0 || !HasInstance || ID >= Instance.AgentTypes.Count) { return(null); } if (!UrbAgentSpawner.SpawnAgent(Instance.AgentTypes[ID], Tile, out var AgentObject, Data)) { return(null); } UrbAgent LoadedAgent = AgentObject.GetComponent <UrbAgent>(); return(LoadedAgent); }
public AgentObject Put(AgentObjectDTO obj) { AgentObject agentObject = new AgentObject(); agentObject = obj.Map <AgentObject>(); SessionManager.DoWork(session => { if (obj.Id == Guid.Empty) { agentObject.Id = Guid.NewGuid(); agentObject.AgentObjectType = new AgentObjectType(); agentObject.AgentObjectType.Id = obj.AgentObjectTypeId; agentObject.AgentObjectDetail = new AgentObjectDetail(); agentObject.AgentObjectDetail.Id = agentObject.Id; agentObject.AgentObjectDetail.NumberOfSection = obj.NumberOfSection; agentObject.AgentObjectDetail.ScienceResearch = obj.ScienceResearch; } else { if (agentObject != null) { agentObject = agentObject = obj.Map <AgentObject>(); agentObject.AgentObjectType = new AgentObjectType(); agentObject.AgentObjectType.Id = obj.AgentObjectTypeId; agentObject.TargetGroupDetails = new List <TargetGroupDetail>(); agentObject.AgentObjectDetail = new AgentObjectDetail(); agentObject.AgentObjectDetail.Id = obj.Id; agentObject.AgentObjectDetail.NumberOfSection = obj.NumberOfSection; agentObject.AgentObjectDetail.ScienceResearch = obj.ScienceResearch; } } foreach (var id in obj.TargetGroupDetailIds) { agentObject.TargetGroupDetails.Add(new TargetGroupDetail() { Id = id }); } session.SaveOrUpdate(agentObject); session.SaveOrUpdate(agentObject.AgentObjectDetail); }); //SessionManager.DoWork(session => session.SaveOrUpdate(obj)); return(agentObject); }
public void AddConnectionMutation(AgentObject agent, int amountTries, MutationLog mutationLog, GeneCounter connectionInnovationCounter) { List <int> nodeKeys = agent.Genome.Nodes.Keys.ToList(); for (int i = 0; i < amountTries; i++) { //Selet two random nodes NodeGene inNode = agent.Genome.Nodes[nodeKeys[Random.Range(0, nodeKeys.Count)]]; NodeGene outNode = agent.Genome.Nodes[nodeKeys[Random.Range(0, nodeKeys.Count)]]; //If mutation is possible, mutate the agent if (agent.Genome.IsConnectionPossible(inNode, outNode)) { int innovationNumber = mutationLog.GetConnectionInnovationNumber(inNode.ID, outNode.ID, connectionInnovationCounter); agent.Genome.AddConnectionMutation(inNode, outNode, innovationNumber); break; } } }
/// <summary> /// Return a list with the best genomes in each species /// </summary> /// <param name="species">the list of species that will be searched</param> /// <returns>the List with the best genomes</returns> public List <Genome> GetBestGenomeForSpecies(List <Species> species) { AgentObject bestAgent = null; List <Genome> bestGenomes = new List <Genome>(); foreach (Species s in species) { s.SortMembersByFitness(); AgentObject agent = s.Members[0]; if (bestAgent == null || bestAgent.GetFitness() <= agent.GetFitness()) { bestAgent = agent; } // species with less than 5 members can not save reproduce if (s.Members.Count < 5) { continue; } if (agent == null) { throw new System.Exception("Agent is null!"); } bestGenomes.Add(agent.Genome); } //If the best agent is not yet in the list (because the species has less then 5 members) add the agenbt if (!bestGenomes.Contains(bestAgent.Genome)) { bestGenomes.Add(bestAgent.Genome); } return(bestGenomes); }
public void KillAgents_Test() { populationManager.CreateInitialPopulation(parent3GenomeSimple, nodeInnovationCounter, connectionInnovationCounter, 100); for (int i = 0; i < resultAgentsInitalizedAgentList.Count; i++) { AgentObject agent = resultAgentsInitalizedAgentList[i]; agent.KillAgent(); Assert.AreEqual(agent, resultAgentKilled); resultAgentKilled = null; //Check if the AllAgentsCallback was invoked after the last agent was killed if (i == resultAgentsInitalizedAgentList.Count - 1) { Assert.True(resultAllAgentsKilled); } else { Assert.False(resultAllAgentsKilled); } } }
public void AddNodeMutation(AgentObject agent, int amountTries, MutationLog mutationLog, GeneCounter connectionInnovationCounter, GeneCounter nodeCounter) { List <int> connectionKeys = agent.Genome.Connections.Keys.OrderBy(x => x).ToList(); if (connectionKeys.Count <= 0) { return; } for (int i = 0; i < amountTries; i++) { ConnectionGene connection = null; //Check the size of the genome, if the genome is small, take an older gene if (agent.Genome.Nodes.Keys.Count <= _SIZE_THRESHOLD) { connection = agent.Genome.Connections[connectionKeys[Random.Range(0, Mathf.RoundToInt(connectionKeys.Count - (Mathf.Sqrt(connectionKeys.Count))))]]; } else { //Select random connection connection = agent.Genome.Connections[connectionKeys[Random.Range(0, connectionKeys.Count)]]; } //If mutation is possible, mutate the agent if (agent.Genome.IsNodePossible(connection)) { //int nodeID = mutationLog.GetNodeID(connection.InnovationNumber, nodeCounter); int nodeID = mutationLog.GetNodeID(connection.InnovationNumber, agent.Genome.Nodes.Keys.ToList(), nodeCounter); int innovationNumberInToNewNode = mutationLog.GetConnectionInnovationNumber(connection.InNode, nodeID, connectionInnovationCounter); int innovationNumberNewNodeToOut = mutationLog.GetConnectionInnovationNumber(nodeID, connection.OutNode, connectionInnovationCounter); agent.Genome.AddNodeMutation(connection, nodeID, innovationNumberInToNewNode, innovationNumberNewNodeToOut); break; } } }
/// <summary> /// Mutate the given agent with different probabilities /// </summary> /// <param name="agent">The agent that should be mutated</param> /// <param name="addConnectionMutationChance">chance to add a connection. Should be between 0f and 1f</param> /// <param name="addNodeMutationChance">chance to add a node. Should be between 0f and 1f</param> /// <param name="mutationWeightChance">chance to mutate the weights. Should be between 0f and 1f</param> /// <param name="nodeInnovationCounter">a node innovation counter</param> /// <param name="connectionInnovationCounter">a connection innovation counter</param> public void MutateAgent(AgentObject agent, float addConnectionMutationChance, float addNodeMutationChance, float mutationWeightChance, GeneCounter nodeInnovationCounter, GeneCounter connectionInnovationCounter, MutationLog mutationLog) { //Mutate weights if (Random.Range(0f, 1f) <= mutationWeightChance) { agent.Genome.MutateConnectionWeight(); } //Mutate Node if (Random.Range(0f, 1f) <= addNodeMutationChance) { AddNodeMutation(agent, _AMOUNT_MUTATION_TRIES, mutationLog, connectionInnovationCounter, nodeInnovationCounter); } //Mutate Connection if (Random.Range(0f, 1f) <= addConnectionMutationChance) { AddConnectionMutation(agent, _AMOUNT_MUTATION_TRIES, mutationLog, connectionInnovationCounter); } }
public AgentObjectDTO GetClass(Guid id) { AgentObjectDTO result = new AgentObjectDTO(); SessionManager.DoWork(session => { AgentObject agentObject = session.Query <AgentObject>().SingleOrDefault(a => a.Id == id); if (agentObject != null) { result = agentObject.Map <AgentObjectDTO>(); foreach (TargetGroupDetail tg in agentObject.TargetGroupDetails) { result.TargetGroupDetailIds.Add(tg.Id); } AgentObjectDetail AgentObjectDetail = session.Query <AgentObjectDetail>().SingleOrDefault(d => d.Id == id); if (AgentObjectDetail != null) { result.NumberOfSection = AgentObjectDetail.NumberOfSection; result.ScienceResearch = AgentObjectDetail.ScienceResearch; } } }); return(result); }
public AgentObject Delete(AgentObject obj) { SessionManager.DoWork(session => session.Delete(obj)); return(obj); //SessionManager.DoWork(session => session.SaveOrUpdate(obj)); }
public void AgentKilledCallback(AgentObject agent) { }
public void AgentKilledCallback(AgentObject agent) { //Reduce Value for GUI _amountAlive -= 1; }
public void GenerateNextGeneration() { //List for new agents List <AgentObject> newGeneration = new List <AgentObject>(); //Put best genomes in new generation without mutation List <Genome> bestGenomes = GetBestGenomeForSpecies(_species); foreach (Genome g in bestGenomes) { Genome copiedGenome = new Genome(g); AgentObject newAgent = _callback.InitNewAgent(this, copiedGenome); newGeneration.Add(newAgent); } //Place species that will be evaluated in the next generation here List <Species> speciesForNextGeneration = new List <Species>(); //Set highest fitness and calculate shared fitness foreach (Species s in _species) { s.SortMembersByFitness(); s.CalculateTotalSharedFitness(); s.SetBestFitness(); s.SelectNewRandomRepresentiveAgent(); s.RemoveHalf(); if (s.IsActive()) { s.IncreaseGeneration(); speciesForNextGeneration.Add(s); } } for (int i = _species.Count - 1; i >= 0; i--) { if (speciesForNextGeneration.Count < 10) { Species s = _species[i]; if (!speciesForNextGeneration.Contains(s)) { speciesForNextGeneration.Add(s); } } else { break; } } //Create remaing Offsprings by Crossover int agentsToCreate = _populationSize - newGeneration.Count; Dictionary <Species, int> randomSpecies = GetAmountOffSpringsForSpecies(agentsToCreate, speciesForNextGeneration); foreach (Species s in randomSpecies.Keys) { //Get twice as much agents as aprents for the crossover List <AgentObject> parentAgents = GetRandomAgentsBiasFitness(randomSpecies[s] * 2, s); for (int i = 0; i < parentAgents.Count; i = i + 2) { AgentObject moreFitParent; AgentObject lessFitParent; if (parentAgents[i].GetFitness() >= parentAgents[i + 1].GetFitness()) { moreFitParent = parentAgents[i]; lessFitParent = parentAgents[i + 1]; } else { moreFitParent = parentAgents[i + 1]; lessFitParent = parentAgents[i]; } //Create new Agent AgentObject child = CrossOverAgent(moreFitParent, lessFitParent); MutateAgent(child, _ADD_CONNECTION_MUTATION_CHANCE, _ADD_NODE_MUTATION_CHANCE, _MUTATE_WEIGHTS_CHANCE, _nodeInnovationCounter, _connectionInnovationCounter, _mutationLog); newGeneration.Add(child); } } //Place the agents in the species PlaceAgentInSpecies(newGeneration, _species); _agents = newGeneration; _generation++; _callback.AgentsInitializedCallback(_agents, _species, _generation); }
public Species(int id, AgentObject representiveAgent) { _id = id; _representiveAgent = representiveAgent; _members = new List <AgentObject>(); }
public void SetUp() { populationManager = new PopulationManager { Callback = this }; //----------------------------------------------------------------------------------- // Parent 1 //----------------------------------------------------------------------------------- parent1Genome = new Genome(); //Create the input nodes parent1Genome.AddNodeGene(new NodeGene(1, NodeGeneType.INPUT, 0f)); parent1Genome.AddNodeGene(new NodeGene(2, NodeGeneType.INPUT, 0f)); parent1Genome.AddNodeGene(new NodeGene(3, NodeGeneType.INPUT, 0f)); //Create the output node parent1Genome.AddNodeGene(new NodeGene(4, NodeGeneType.OUTPUT, 1f)); //Create hidden node parent1Genome.AddNodeGene(new NodeGene(5, NodeGeneType.HIDDEN, 0.5f)); //Create connections parent1Genome.AddConnectionGene(new ConnectionGene(1, 4, 1.0, true, 1)); parent1Genome.AddConnectionGene(new ConnectionGene(2, 4, 1.0, false, 2)); parent1Genome.AddConnectionGene(new ConnectionGene(3, 4, 1.0, true, 3)); parent1Genome.AddConnectionGene(new ConnectionGene(2, 5, 1.0, true, 4)); parent1Genome.AddConnectionGene(new ConnectionGene(5, 4, 1.0, true, 5)); parent1Genome.AddConnectionGene(new ConnectionGene(1, 5, 1.0, true, 8)); //----------------------------------------------------------------------------------- // Parent 2 //----------------------------------------------------------------------------------- parent2Genome = new Genome(); //Create the input nodes parent2Genome.AddNodeGene(new NodeGene(1, NodeGeneType.INPUT, 0f)); parent2Genome.AddNodeGene(new NodeGene(2, NodeGeneType.INPUT, 0f)); parent2Genome.AddNodeGene(new NodeGene(3, NodeGeneType.INPUT, 0f)); //Create the output node parent2Genome.AddNodeGene(new NodeGene(4, NodeGeneType.OUTPUT, 1f)); //Create hidden node parent2Genome.AddNodeGene(new NodeGene(5, NodeGeneType.HIDDEN, 0.4f)); parent2Genome.AddNodeGene(new NodeGene(6, NodeGeneType.HIDDEN, 0.5f)); //Create connections parent2Genome.AddConnectionGene(new ConnectionGene(1, 4, 1.0, true, 1)); parent2Genome.AddConnectionGene(new ConnectionGene(2, 4, 1.0, false, 2)); parent2Genome.AddConnectionGene(new ConnectionGene(3, 4, 1.0, true, 3)); parent2Genome.AddConnectionGene(new ConnectionGene(2, 5, 1.0, true, 4)); parent2Genome.AddConnectionGene(new ConnectionGene(5, 4, 1.0, false, 5)); parent2Genome.AddConnectionGene(new ConnectionGene(5, 6, 1.0, true, 6)); parent2Genome.AddConnectionGene(new ConnectionGene(6, 4, 1.0, true, 7)); parent2Genome.AddConnectionGene(new ConnectionGene(3, 5, 1.0, true, 9)); parent2Genome.AddConnectionGene(new ConnectionGene(1, 6, 1.0, true, 10)); //----------------------------------------------------------------------------------- // Parent 3 //----------------------------------------------------------------------------------- parent3GenomeSimple = new Genome(); //Create the input nodes parent3GenomeSimple.AddNodeGene(new NodeGene(7, NodeGeneType.INPUT, 0f)); parent3GenomeSimple.AddNodeGene(new NodeGene(8, NodeGeneType.INPUT, 0f)); parent3GenomeSimple.AddNodeGene(new NodeGene(9, NodeGeneType.INPUT, 0f)); //Create the output node parent3GenomeSimple.AddNodeGene(new NodeGene(10, NodeGeneType.OUTPUT, 1f)); //Create connections parent3GenomeSimple.AddConnectionGene(new ConnectionGene(7, 10, 1.0, true, 11)); parent3GenomeSimple.AddConnectionGene(new ConnectionGene(8, 10, 1.0, true, 12)); parent3GenomeSimple.AddConnectionGene(new ConnectionGene(9, 10, 1.0, true, 13)); //Init the connection gene counter with 11 connectionInnovationCounter = new GeneCounter(14); nodeInnovationCounter = new GeneCounter(11); //Set result values from callback to null resultAgentsInitalizedAgentList = null; resultAgentsInitializedSpeciesList = null; resultAgentKilled = null; resultAllAgentsKilled = false; //Set fine tuning parameters PopulationManager._FACTOR_EXCESS_GENES = 1; PopulationManager._FACTOR_DISJOINT_GENES = 1; PopulationManager._FACTOR_AVG_WEIGHT_DIF = 0.4f; PopulationManager._THRESHOLD_NUMBER_OF_GENES = 20; PopulationManager._COMPABILITY_THRESHOLD = 3; }
public void AgentKilledCallback(AgentObject agent) { resultAgentKilled = agent; }
public IEnumerable <StaffDTO> GetViceDepartmentStaff(int typeId, Guid departmentId, Guid planId) { var result = new List <StaffDTO>(); SessionManager.DoWork(session => { if (departmentId == Guid.Empty) { departmentId = ControllerHelpers.GetCurrentStaff(session).Department.Id; } int selectedTypeId = 0; switch (typeId) { case (int)AgentObjectTypes.Khoa: { selectedTypeId = (int)AgentObjectTypes.PhoKhoa; } break; case (int)AgentObjectTypes.PhongBan: { selectedTypeId = (int)AgentObjectTypes.PhoPhongBan; } break; case (int)AgentObjectTypes.HieuTruong: { selectedTypeId = (int)AgentObjectTypes.PhoHieuTruong; } break; } IQueryable <Staff> resultQuery = session.Query <Staff>().Where(s => s.Department.Id == departmentId && s.StaffStatus.NoLongerWork == 0 && s.StaffProfile.GCRecord == null && (s.StaffInfo.Position.AgentObjectType.Id == selectedTypeId || s.StaffInfo.SubPositions.Any(p => p.Position.AgentObjectType.Id == selectedTypeId))); //IQueryable<Staff> resultQuery = null; //resultQuery = session.Query<Staff>().Where(a => a.StaffInfo.Position.AgentObjectType.ParentAgentObjectType.Id == typeId).AsQueryable(); if (departmentId != Guid.Empty) { List <Staff> listtemp = resultQuery.Where(s => s.Department.Id == departmentId).ToList(); foreach (Staff st in listtemp) { StaffDTO std = ParseFullStaff(st); result.Add(std); } foreach (StaffDTO s in result) { AgentObject a = session.Query <AgentObject>().Where(ag => ag.AgentObjectType.Id == selectedTypeId).FirstOrDefault(); s.AgentObjectId = a != null ? a.Id : Guid.Empty; } } else { List <Staff> listtemp = resultQuery.ToList(); foreach (Staff st in listtemp) { StaffDTO std = ParseFullStaff(st); result.Add(std); } } foreach (StaffDTO st in result) { st.IsApproved = false; st.IsStaffRated = false; st.IsSupervisorRated = false; PlanStaff planStaff = session.Query <PlanStaff>().Where(p => p.PlanKPI.Id == planId && p.Staff.Id == st.Id && p.AgentObjectType.Id == st.AgentObjectTypeId).SingleOrDefault(); if (planStaff != null) { //Kế hoạch được trưởng phòng duyệt st.IsApproved = planStaff.IsLocked; Result rs = session.Query <Result>().Where(r => r.PlanStaff.Id == planStaff.Id).SingleOrDefault(); if (rs != null) { //Trưởng phòng đánh giá st.IsSupervisorRated = rs.TotalRecord > 0 ? true : false; //Nhân viên đã đánh giá st.IsStaffRated = rs.TempRecord > 0 || st.IsSupervisorRated == true ? true : false; } } } }); return(result); }
public IEnumerable <StaffDTO> GetDepartmentStaff(int agentObjectTypeId, Guid planId) { List <StaffDTO> result = new List <StaffDTO>(); SessionManager.DoWork(session => { Staff staff = ControllerHelpers.GetCurrentStaff(session); Guid staffId = staff.Id; switch (agentObjectTypeId) { case (int)AgentObjectTypes.PhongBan: { List <Staff> stafflist = session.Query <Staff>().Where(s => s.Department.Id == staff.Department.Id && s.StaffStatus.NoLongerWork == 0 && s.StaffProfile.GCRecord == null && s.StaffInfo.Position == null).ToList(); foreach (Staff s in stafflist) { if (s.Id != staffId) { StaffDTO sd = new StaffDTO(); sd.Name = s.StaffProfile.Name; sd.Id = s.Id; sd.AgentObjectIds = new List <Guid>(); //if (staff.StaffInfo.Position == null) //{ AgentObject ao = session.Query <AgentObject>().SingleOrDefault(a => a.AgentObjectType.Id == 2); sd.AgentObjectIds.Add(ao.Id); //} //else //{ // foreach (AgentObject a in s.StaffInfo.AgentObjects) // { // if (a.AgentObjectType.Id == 2) // { // sd.AgentObjectIds.Add(a.Id); // } // } //} if (sd.AgentObjectIds.Count > 0) { sd.AgentObjectId = sd.AgentObjectIds.FirstOrDefault(); } sd.IsApproved = false; sd.IsStaffRated = false; sd.IsSupervisorRated = false; PlanStaff planStaff = session.Query <PlanStaff>().Where(p => p.PlanKPI.Id == planId && p.Staff.Id == s.Id && p.Department == null).SingleOrDefault(); if (planStaff != null) { //Kế hoạch được trưởng phòng duyệt sd.IsApproved = planStaff.IsLocked; Result rs = session.Query <Result>().Where(r => r.PlanStaff.Id == planStaff.Id).SingleOrDefault(); if (rs != null) { //Trưởng phòng đánh giá sd.IsSupervisorRated = rs.TotalRecord > 0? true : false; //Nhân viên đã đánh giá sd.IsStaffRated = rs.TempRecord > 0 || sd.IsSupervisorRated == true ? true : false; } } result.Add(sd); } } } break; //User có cả 3 kế hoạch năm hk tháng case 100: { List <Staff> stafflist = session.Query <Staff>().Where(s => s.Department.Id == staff.Department.Id && s.StaffStatus.NoLongerWork == 0 && s.StaffProfile.GCRecord == null && s.StaffProfile.GCRecord == null).ToList(); foreach (Staff s in stafflist) { if (s.Id != staffId) { StaffDTO sd = new StaffDTO(); sd.Name = s.StaffProfile.Name; sd.Id = s.Id; sd.AgentObjectIds = new List <Guid>(); foreach (AgentObject a in s.StaffInfo.AgentObjects) { if (a.AgentObjectType.Id == 2) { sd.AgentObjectIds.Add(a.Id); } } if (sd.AgentObjectIds.Count > 0) { sd.AgentObjectId = sd.AgentObjectIds.FirstOrDefault(); } sd.IsApproved = false; sd.IsStaffRated = false; sd.IsSupervisorRated = false; PlanStaff planStaff = session.Query <PlanStaff>().Where(p => p.PlanKPI.Id == planId && p.Staff.Id == s.Id && p.Department == null).SingleOrDefault(); if (planStaff != null) { //Kế hoạch được trưởng phòng duyệt sd.IsApproved = planStaff.IsLocked; Result rs = session.Query <Result>().Where(r => r.PlanStaff.Id == planStaff.Id).SingleOrDefault(); if (rs != null) { //Trưởng phòng đánh giá sd.IsSupervisorRated = rs.TotalRecord > 0 && rs.IsLocked == true ? true : false; //Nhân viên đã đánh giá sd.IsStaffRated = (rs.TotalRecord > 0 && rs.IsLocked == false) || sd.IsSupervisorRated == true ? true : false; } } result.Add(sd); } } } break; case (int)AgentObjectTypes.BoMon: { List <Staff> stafflist = session.Query <Staff>().Where(s => s.StaffInfo.Subject.Id == staff.StaffInfo.Subject.Id && s.StaffStatus.NoLongerWork == 0 && s.StaffProfile.GCRecord == null && s.StaffProfile.GCRecord == null).ToList(); foreach (Staff s in stafflist) { if (s.Id != staffId) { StaffDTO sd = new StaffDTO(); sd.Name = s.StaffProfile.Name; sd.Id = s.Id; sd.AgentObjectIds = new List <Guid>(); foreach (AgentObject a in s.StaffInfo.AgentObjects) { if (a.AgentObjectType.Id == 1) { sd.AgentObjectIds.Add(a.Id); } } if (sd.AgentObjectIds.Count > 0) { sd.AgentObjectId = sd.AgentObjectIds.FirstOrDefault(); } sd.IsApproved = false; sd.IsStaffRated = false; sd.IsSupervisorRated = false; PlanStaff planStaff = session.Query <PlanStaff>().Where(p => p.PlanKPI.Id == planId && p.Staff.Id == s.Id && p.Department == null).SingleOrDefault(); if (planStaff != null) { //Kế hoạch được trưởng bộ môn duyệt sd.IsApproved = planStaff.IsLocked; Result rs = session.Query <Result>().Where(r => r.PlanStaff.Id == planStaff.Id).SingleOrDefault(); if (rs != null) { //Trưởng bộ môn đánh giá sd.IsSupervisorRated = rs.TotalRecord > 0 && rs.IsLocked == true ? true : false; //Giảng viên đã đánh giá sd.IsStaffRated = (rs.TotalRecord > 0 && rs.IsLocked == false) || sd.IsSupervisorRated == true ? true : false; } } result.Add(sd); } } } break; case (int)AgentObjectTypes.Khoa: { List <Staff> stafflist = session.Query <Staff>().Where(s => s.Department.Id == staff.Department.Id && s.StaffStatus.NoLongerWork == 0 && s.StaffProfile.GCRecord == null && (s.StaffInfo.Position.AgentObjectType.Id == 8 || s.StaffInfo.SubPositions.Any(p => p.Position.AgentObjectType.Id == 8))).ToList(); foreach (Staff s in stafflist) { if (s.Id != staffId) { StaffDTO sd = new StaffDTO(); sd.Name = s.StaffProfile.Name; sd.Id = s.Id; AgentObject a = session.Query <AgentObject>().Where(ag => ag.AgentObjectType.Id == 8).FirstOrDefault(); sd.AgentObjectId = a != null ? a.Id : Guid.Empty; sd.IsApproved = false; sd.IsStaffRated = false; sd.IsSupervisorRated = false; PlanStaff planStaff = session.Query <PlanStaff>().Where(p => p.PlanKPI.Id == planId && p.Staff.Id == s.Id && p.Department == null).SingleOrDefault(); if (planStaff != null) { //Kế hoạch được trưởng khoa duyệt sd.IsApproved = planStaff.IsLocked; Result rs = session.Query <Result>().Where(r => r.PlanStaff.Id == planStaff.Id).SingleOrDefault(); if (rs != null) { //Trưởng khoa đánh giá sd.IsSupervisorRated = rs.TotalRecord > 0 && rs.IsLocked == true ? true : false; //Phó trưởng khoa đã đánh giá sd.IsStaffRated = (rs.TotalRecord > 0 && rs.IsLocked == false) || sd.IsSupervisorRated == true ? true : false; } } result.Add(sd); } } } break; } }); return(result); }