示例#1
0
        public async void GetPathway_should_return_a_single_pathway_by_id_before_adding_to_cache()
        {
            //Arrange
            var id      = "PW123";
            var pathway = new Pathway {
                Title = "pathway1", Id = "PW12"
            };
            var expectedCacheKey = new PathwayCacheKey(id);

            _cacheManagerMock.Setup(x => x.Read(It.IsAny <string>())).ReturnsAsync(string.Empty);
            var response = new Mock <IRestResponse <Pathway> >();

            response.Setup(_ => _.Data).Returns(pathway);

            _restClient.Setup(x => x.ExecuteAsync <Pathway>(It.IsAny <IRestRequest>()))
            .ReturnsAsync(response.Object);

            var sut = new PathwayService(_configuration.Object, _restClient.Object, _cacheStoreMock);

            //Act
            var result = await sut.GetPathway(id);

            //Assert
            _cacheManagerMock.Verify(x => x.Set(expectedCacheKey.CacheKey, It.IsAny <string>()), Times.Once);
            _configuration.Verify(x => x.GetDomainApiPathwayUrl(id), Times.Once);
            _restClient.Verify(x => x.ExecuteAsync <Pathway>(It.IsAny <IRestRequest>()), Times.Once);
            Assert.AreEqual(result.Title, "pathway1");
        }
    private IEnumerator SetTarget()
    {
        Debug.Log("starting SetTarget");
        Debug.Log(Tour.pathways);
        rb.transform.position = new Vector3(Tour.pathways[0].GetPoints()[0].x, Tour.pathways[0].GetPoints()[0].y, Tour.pathways[0].GetPoints()[0].z);

        for (int p = 0; p < Tour.pathways.Count; p++)
        {
            currentPath = Tour.pathways[p];
            Debug.Log("in tour, going to next path:   " + currentPath.GetName() + "   :   " + p);
            for (int i = 0; i < currentPath.GetPointsLength() - 1; i++)
            {
                startPos = new Vector3(currentPath.GetPoints()[i].x, currentPath.GetPoints()[i].y, currentPath.GetPoints()[i].z);
                target   = new Vector3(currentPath.GetPoints()[i + 1].x, currentPath.GetPoints()[i + 1].y, currentPath.GetPoints()[i + 1].z);

                yield return(new WaitForSeconds(lerpTime));

                Debug.Log("going to next point: " + (i + 1));
            }
            startPos = currentPath.GetPoints()[currentPath.GetPointsLength() - 1];
            target   = currentPath.GetPoints()[currentPath.GetPointsLength() - 1];
            yield return(new WaitForSeconds(lerpTime));
        }


        StartCoroutine("SetTarget");
    }
示例#3
0
        public async void should_return_an_identified_pathway()
        {
            //Arrange

            var url = "http://mytest.com/";

            var pathwayNo = "PW755";
            var gender    = "Male";
            var age       = 35;
            var pathway   = new Pathway {
                Title = "identified pathway"
            };

            var response = new Mock <IRestResponse <Pathway> >();

            response.Setup(_ => _.Data).Returns(pathway);

            _configuration.Setup(x => x.GetDomainApiIdentifiedPathwayUrl(pathwayNo, gender, age)).Returns(url);
            _restClient.Setup(x => x.ExecuteAsync <Pathway>(It.IsAny <IRestRequest>()))
            .ReturnsAsync(response.Object);

            var sut = new PathwayService(_configuration.Object, _restClient.Object, _cacheStoreMock);

            //Act
            var result = await sut.GetIdentifiedPathway(pathwayNo, gender, age);

            //Assert
            _configuration.Verify(x => x.GetDomainApiIdentifiedPathwayUrl(pathwayNo, gender, age), Times.Once);
            _restClient.Verify(x => x.ExecuteAsync <Pathway>(It.IsAny <IRestRequest>()), Times.Once);
            Assert.AreEqual(result.Title, "identified pathway");
        }
示例#4
0
    public List <Tile> TrimWall(Pathway p)
    {
        List <Tile> destroyed = new List <Tile>();

        if (p == Pathway.BOTTOM && bottom_wall != null)
        {
            Destroy(bottom_wall);
            _bottom_connection = false;
            destroyed.AddRange(bottom_wall.GetComponentsInChildren <Tile>());
        }
        else if (p == Pathway.LEFT && left_wall != null)
        {
            Destroy(left_wall);
            _left_connection = false;
            destroyed.AddRange(left_wall.GetComponentsInChildren <Tile>());
        }
        else if (p == Pathway.RIGHT && right_wall != null)
        {
            Destroy(right_wall);
            _right_connection = false;
            destroyed.AddRange(right_wall.GetComponentsInChildren <Tile>());
        }
        else if (p == Pathway.TOP && top_wall != null)
        {
            Destroy(top_wall);
            _top_connection = false;
            destroyed.AddRange(top_wall.GetComponentsInChildren <Tile>());
        }
        return(destroyed);
    }
示例#5
0
        public async Task <PageDataViewModel> PageDataBuilder(PageDataViewModel model)
        {
            model.Date = DateTime.Now.Date.ToShortDateString();
            model.Time = DateTime.Now.ToString("HH:mm:ss");

            Pathway currentPathway = null;

            if (!string.IsNullOrEmpty(model.QuestionId) && model.QuestionId.Contains("."))
            {
                var currentPathwayNo = model.QuestionId.Split('.')[0];
                if (!currentPathwayNo.Equals(model.StartingPathwayNo))
                {
                    var businessApiPathwayUrl = _configuration.GetBusinessApiPathwayIdUrl(currentPathwayNo, model.Gender, new AgeCategory(model.Age).MinimumAge);
                    var response = await _restClient.ExecuteAsync <Pathway>(new JsonRestRequest(businessApiPathwayUrl, Method.GET));

                    CheckResponse(response);

                    currentPathway = response.Data;
                }
            }
            model.PathwayNo    = (currentPathway != null) ? currentPathway.PathwayNo : string.Empty;
            model.PathwayTitle = (currentPathway != null) ? currentPathway.Title : string.Empty;

            return(model);
        }
 private void CreatePathwayNode(Pathway newPathway)
 {
     GraphRepository.Client.Cypher
     .Create("(p:Pathway {newPathway})")
     .WithParam("newPathway", newPathway)
     .ExecuteWithoutResults();
 }
示例#7
0
 public WSTask(string name, string link, Element container, Pathway result)
 {
     Name      = name;
     Link      = link;
     Container = container;
     Pathways.Add(result);
 }
示例#8
0
        public List <Pathway> SearchPathway(string search)
        {
            List <Pathway> list = null;

            dataProvider.ExecuteCmd("dbo.Pathway_PathwaySearch"
                                    , inputParamMapper : delegate(SqlParameterCollection paramCollection)
            {
                paramCollection.AddWithValue("@search", search);
            }
                                    , singleRecordMapper : delegate(IDataReader reader, short set)
            {
                Pathway singleItem = new Pathway();
                int startingIndex  = 0;

                singleItem.Id          = reader.GetSafeInt32(startingIndex++);
                singleItem.Name        = reader.GetSafeString(startingIndex++);
                singleItem.Description = reader.GetSafeString(startingIndex++);
                singleItem.Topics      = reader.GetSafeString(startingIndex++);

                if (list == null)
                {
                    list = new List <Pathway>();
                }

                list.Add(singleItem);
            }
                                    );

            return(list);
        }
 /// <summary>
 /// Awake this instance.
 /// </summary>
 void Awake()
 {
     path = GetComponentInParent <Pathway>();
     // Load enemies prefabs from specified directory
     enemyPrefabs = Resources.LoadAll <GameObject>(enemiesResourceFolder).ToList();
     Debug.Assert((path != null) && (enemyPrefabs != null), "Wrong initial parameters");
 }
        private int HandlePathwayComponent(PathwayComponent input, Pathway pathway, ref PathwayComponent output, ref bool recordExists, ref SaveStatus status)
        {
            List <string> messages = new List <string>();

            //the record may be ready to save??
            //
            if (DoesComponentExist(input, pathway.CTID, ref output))
            {
                input.Id     = output.Id;
                recordExists = true;
                //delete any existing conditions
                new PathwayComponentConditionManager().DeleteAll(input.Id, status);
            }
            else
            {
                output.PathwayCTID = pathway.CTID;
                //if ( BaseFactory.IsGuidValid( input.RowId ) )
                //	output.RowId = input.RowId;
            }

            new PathwayComponentManager().Save(input, ref status);


            return(input.Id);
        }
示例#11
0
 /// <summary>
 /// Raises the state enter event.
 /// </summary>
 /// <param name="previousState">Previous state.</param>
 /// <param name="newState">New state.</param>
 public override void OnStateEnter(AiState previousState, AiState newState)
 {
     if (path == null)
     {
         // If I have no path - try to find it
         path = FindObjectOfType <Pathway>();
         Debug.Assert(path, "Have no path");
     }
     if (destination == null)
     {
         // Get next waypoint from my path
         destination = path.GetNearestWaypoint(transform.position);
     }
     // Set destination for navigation agent
     aiBehavior.navAgent.destination = destination.transform.position;
     // Start moving
     aiBehavior.navAgent.move = true;
     aiBehavior.navAgent.turn = true;
     // If unit has animator
     if (anim != null && anim.runtimeAnimatorController != null)
     {
         // Search for clip
         foreach (AnimationClip clip in anim.runtimeAnimatorController.animationClips)
         {
             if (clip.name == "Move")
             {
                 // Play animation
                 anim.SetTrigger("move");
                 break;
             }
         }
     }
 }
示例#12
0
 //设置正在旋转这的圆
 public void SetCircle(Circle circle)
 {
     myCircle     = circle;
     rotateRadius = myCircle.m_Radius - pHalfWidth;
     pathway      = Pathway.inPath;
     rotateSpeed  = rotateDis / rotateRadius;
 }
示例#13
0
        public IEnumerable <AttendanceVM> GetAttendanceByPathway(Pathway pathway)
        {
            List <Attendance>   attendances = new List <Attendance>().Where(f => f.Trainee.Pathway == pathway).ToList();
            List <AttendanceVM> models      = new List <AttendanceVM>();

            foreach (var attendance in attendances)
            {
                models.Add(new AttendanceVM
                {
                    TraineeId = attendance.TraineeId,
                    MarkedBy  = attendance.MarkedBy,
                    February  = attendance.February,
                    March     = attendance.March,
                    April     = attendance.April,
                    May       = attendance.May,
                    June      = attendance.June,
                    July      = attendance.July,
                    August    = attendance.August,
                    September = attendance.September,
                    October   = attendance.October,
                    November  = attendance.November
                });
            }
            return(models);
        }
        public ArrangementPageViewModel(InteriorField[,] layout, Chair chairModel, Table tableModel)
        {
            this.Rows = layout.GetLength(0);
            this.Columns = layout.GetLength(1);
            this.Arrangement = new ObservableCollection<ArrangedFieldViewModel>();
            for (int y = 0; y < layout.GetLength(0); y++)
                for (int x = 0; x < layout.GetLength(1); x++)
                {
                    this.Arrangement.Add(new ArrangedFieldViewModel((layout[y, x])));
                }

            this.Palettes = new ObservableCollection<string>(new[] { "Light", "Dark" });
            this.ChairModel = chairModel;
            this.TableModel = tableModel;

            Pathway autoPathway = new Pathway();
            Flower autoFlower = new Flower();
            foreach (ArrangedFieldViewModel field in this.Arrangement)
            {
                if (field?.PlaceHolder?.CanHoldObject(autoFlower) ?? false) field.ArrangeObjectCommand.Execute(autoFlower);
                else if (field?.PlaceHolder?.CanHoldObject(autoPathway) ?? false) field.ArrangeObjectCommand.Execute(autoPathway);
            }

            this.ClearAllCommand = new DelegateCommand((param) => this.ClearAll());
            this.FillAllCommand = new DelegateCommand((param) => this.FillAll());
            this.RemoveObjectCommand = new DelegateCommand(this.RemoveObject, this.CanRemoveObject);
        }
示例#15
0
    private static void DrawHandlesPath(Pathway pathway)
    {
        if (pathway.Waypoints.Count != 0)
        {
            DrawElements(pathway, pathway.Waypoints, 0);
        }

        for (int i = 0; i < pathway.Waypoints.Count; i++)
        {
            if (i != 0 && pathway.Waypoints.Count > 1)
            {
                DrawElements(pathway, pathway.Waypoints, i);
                using (new Handles.DrawingScope(pathway.LineColor))
                {
                    Handles.DrawDottedLine(pathway.Waypoints[i - 1], pathway.Waypoints[i], 2);
                }
            }
        }

        if (pathway.Waypoints.Count > 2)
        {
            using (new Handles.DrawingScope(pathway.LineColor))
            {
                Handles.DrawDottedLine(pathway.Waypoints[0], pathway.Waypoints[pathway.Waypoints.Count - 1], 2);
            }
        }
    }
示例#16
0
    bool NewPathOverlap(Pathway newPath)
    {
        //Debug.Break();
        Debug.Log(debugger);
        debugger++;
        GameObject pathCollider = newPath.transform.Find("PathColl").gameObject;
        Bounds     bounds       = pathCollider.GetComponent <BoxCollider>().bounds;

        Collider[] colliders = Physics.OverlapBox(bounds.center, bounds.size / 1.8f, pathCollider.transform.rotation, pathLayerMask);

        foreach (Collider coll in colliders)
        {
            Debug.Log(coll);
        }

        if (colliders.Length > 0)
        {
            foreach (Collider c in colliders)
            {
                if (c.gameObject == pathCollider.gameObject)
                {
                    continue;
                }
                else
                {
                    Debug.Log("Collision");
                    return(true);
                }
            }
        }
        Debug.Log("NoColl");
        return(false);
    }
示例#17
0
        public Pathway SelectPathwayById(int id)
        {
            Pathway singleItem = null;

            dataProvider.ExecuteCmd("dbo.Pathway_SelectById"
                                    , inputParamMapper : delegate(SqlParameterCollection paramCollection)
            {
                paramCollection.AddWithValue("@Id", id);
            }
                                    , singleRecordMapper : delegate(IDataReader reader, short set)
            {
                singleItem        = new Pathway();
                int startingIndex = 0;

                singleItem.Id          = reader.GetSafeInt32(startingIndex++);
                singleItem.Name        = reader.GetSafeString(startingIndex++);
                singleItem.Description = reader.GetSafeString(startingIndex++);
                singleItem.CoverImage  = reader.GetSafeInt32(startingIndex++);
                singleItem.Topics      = reader.GetSafeString(startingIndex++);

                if (singleItem == null)
                {
                    singleItem = new Pathway();
                }
            }
                                    );
            return(singleItem);
        }
 private void WalkPathEventAction(bool status, Pathway path, Scene targetScene, List<string> messages)
 {
     if (status)
     {
         GameGlobal.Player.Location = targetScene;
         if (targetScene is Wilderness)
         {
             Wilderness targetWilderness = targetScene as Wilderness;
             if (!targetWilderness.discoveredPaths.Contains(path))
                 targetWilderness.discoveredPaths.Add(path);
             targetWilderness.messages.Clear();
             foreach(string message in messages)
                 targetWilderness.messages.Enqueue(message);
         }
         if (targetScene is Town)
         {
             Application.LoadLevel("TownScene");
         }
         else if (targetScene is ResourcePoint)
         {
             Application.LoadLevel("ResourcePointScene");
         }
         else if (targetScene is Wilderness)
         {
             Application.LoadLevel("WildernessScene");
         }
     }
 }
示例#19
0
        /// <summary>
        /// Instructs Vehicle Entity to always stay on the provided path. Entity will move to the nearest point
        /// </summary>
        /// <param name="vehicle"></param>
        /// <param name="predictionTime"></param>
        /// <param name="path"></param>
        /// <returns>The Vector to move to</returns>
        public static Vector3 StayOnPath(VehicleActor vehicle, float predictionTime, Pathway path)
        {
            // predict our future position
            Vector3 futurePosition = vehicle.PredictFuturePosition(predictionTime);

            // find the point on the path nearest the predicted future position
            Vector3 tangent;
            float   outside;
            Vector3 onPath = path.MapPointToPath(futurePosition, out tangent, out outside);

            if (outside < 0)
            {
                // our predicted future position was in the path,
                // return zero steering.
                return(Vector3.Zero);
            }
            else
            {
                // our predicted future position was outside the path, need to
                // steer towards it.  Use onPath projection of futurePosition
                // as seek target
                //log PathFollowing(futurePosition, onPath, onPath, outside);
                return(Seek(vehicle, onPath));
            }
        }
示例#20
0
        public ActionResult Add(AddPathwayInputModel pathwayInputModel)
        {
            if (ModelState.IsValid)
            {
                using (var unitOfwork = new UnitOfWork())
                {
                    var pathway = new Pathway
                    {
                        PPINumber        = pathwayInputModel.PPINumber,
                        Patient          = GetPatientByNhsNumber(pathwayInputModel.SelectedPatientNHSNumber, unitOfwork),
                        OrganizationCode = pathwayInputModel.OrganizationCode
                    };

                    pathway.ValidationFailed += ruleViolation =>
                    {
                        ruleViolation.CreatedAt = DateTime.UtcNow;
                        unitOfwork.RuleViolations.Add(ruleViolation);
                    };
                    pathway.Validate();

                    unitOfwork.Pathways.Add(pathway);
                    unitOfwork.SaveChanges();
                }

                return(RedirectToAction("Add"));
            }

            pathwayInputModel.Patients    = GetAllPatients();
            pathwayInputModel.AllPathways = GetAllPathways();

            return(View(pathwayInputModel));
        }
示例#21
0
        private async void submit_Click(object sender, RoutedEventArgs e)
        {
            InputValues inputValues = new InputValues();

            inputValues.Age                     = Int32.Parse(age.Text);
            inputValues.BlurredVision           = GetIntValueFromChoices(visionYes);
            inputValues.Diabetic                = GetIntValueFromChoices(diabeticYes);
            inputValues.DopplerHBeatCount       = GetIntValueFromChoices(countYes);
            inputValues.FatigueLevel            = ((ComboBoxItem)fatigueLevels.SelectedItem).Name;
            inputValues.FeelThirsty             = GetIntValueFromChoices(thirstyYes);
            inputValues.FrequentFetalMovements  = GetIntValueFromChoices(movementsYes);
            inputValues.FrequentUrination       = GetIntValueFromChoices(urinateYes);
            inputValues.FundusHeightBeyondRange = GetIntValueFromChoices(rangeYes);
            inputValues.HcGLevel                = ((ComboBoxItem)hcGValues.SelectedItem).Name;
            inputValues.Hypertension            = GetIntValueFromChoices(highBPYes);
            inputValues.PastHypertensionHistory = GetIntValueFromChoices(hyperHistoryYes);
            inputValues.SugarLevelInUrine       = float.Parse(urinesugar.Text);
            inputValues.UltrasoundConfirmation  = ((ComboBoxItem)usConfirmations.SelectedItem).Name;
            inputValues.WeightGain              = GetIntValueFromChoices(weightYes);

            var result = await ContextualCareServiceProxy.InvokeRequestResponseService(inputValues);

            var     jsonResult = JsonConvert.DeserializeObject(result);
            Pathway pathway    = ExtractAndConvertToPathway(jsonResult);
        }
示例#22
0
        private void bEditEl_Click(object sender, EventArgs e)
        {
            if (DGVElements.SelectedRows.Count == 0)
            {
                return;
            }
            int id = int.Parse(DGVElements.SelectedRows[0].Cells["colEId"].Value.ToString());

            Pathway pw      = null;
            Element element = null;

            for (int p = 0; p < task.Pathways.Count; p++)
            {
                for (int el = 0; el < task.Pathways[p].elements.Count && pw == null; el++)
                {
                    if (task.Pathways[p].elements[el].Id == id)
                    {
                        pw      = task.Pathways[p];
                        element = task.Pathways[p].elements[el];
                        break;
                    }
                }
            }
            ShowPanel("pElement", new object[] { element, currentPanel.Name, currentPanel.Tag, pw });
        }
示例#23
0
        public async void GetPathway_should_return_a_single_pathway_by_id()
        {
            //Arrange

            var url     = "http://mytest.com/";
            var id      = "PW123";
            var pathway = new Pathway {
                Title = "pathway1"
            };

            var response = new Mock <IRestResponse <Pathway> >();

            response.Setup(_ => _.Data).Returns(pathway);

            _configuration.Setup(x => x.GetDomainApiPathwayUrl(id)).Returns(url);
            _restClient.Setup(x => x.ExecuteAsync <Pathway>(It.IsAny <IRestRequest>()))
            .ReturnsAsync(response.Object);

            var sut = new PathwayService(_configuration.Object, _restClient.Object, _cacheStoreMock);

            //Act
            var result = await sut.GetPathway(id);

            //Assert
            _configuration.Verify(x => x.GetDomainApiPathwayUrl(id), Times.Once);
            _restClient.Verify(x => x.ExecuteAsync <Pathway>(It.IsAny <IRestRequest>()), Times.Once);
            Assert.AreEqual(result.Title, "pathway1");
        }
示例#24
0
        private void GeneratePathways_Click(object sender, EventArgs e)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var patients = unitOfWork.Patients.ToList();

                var pathwayCount = string.IsNullOrEmpty(txtPathwayCount.Text) ? 3000 : Int32.Parse(txtPathwayCount.Text);

                for (var pathwayIndex = 0; pathwayIndex < pathwayCount; pathwayIndex++)
                {
                    var pathway = new Pathway
                    {
                        OrganizationCode = "org" + pathwayIndex,
                        Patient          = patients[_random.Next(0, patients.Count - 1)],
                        PPINumber        = GetUniqueIndex("123456", pathwayIndex)
                    };

                    unitOfWork.Pathways.Add(pathway);
                    Console.WriteLine("Added pathway {0} to UOW", pathway.PPINumber);
                }

                Console.WriteLine("Persisting UOW to DB...");
                unitOfWork.SaveChanges();
                Console.WriteLine("Done adding pathways!");
            }
        }
        public static List <int> GetAllIds(Guid parentUid)
        {
            List <int> list   = new List <int>();
            Pathway    entity = new Pathway();

            Entity parent = EntityManager.GetEntity(parentUid);

            LoggingHelper.DoTrace(7, string.Format("Entity_Pathway_GetAll: parentUid:{0} entityId:{1}, e.EntityTypeId:{2}", parentUid, parent.Id, parent.EntityTypeId));

            try
            {
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.Entity_HasPathway
                                              .Where(s => s.EntityId == parent.Id)
                                              .OrderBy(s => s.Pathway.Name)             //not sure
                                              .ToList();

                    if (results != null && results.Count > 0)
                    {
                        foreach (DBEntity item in results)
                        {
                            list.Add(item.PathwayId);
                        }
                    }
                    return(list);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".Entity_Pathway_GetAll");
            }
            return(list);
        }
示例#26
0
 private void AddConnectionPoints(Pathway pathway)
 {
     foreach (ConnectionPoint connpoint in pathway.connectionPoints)
     {
         int r = Random.Range(0, sectionConnectionPoints.Count);
         sectionConnectionPoints.Insert(r, connpoint);
     }
     return;
 }
示例#27
0
 private void AddPeriodToPathway(Pathway pathway, Period period, UnitOfWork unitOfWork)
 {
     pathway.ValidationFailed += ruleViolation =>
     {
         ruleViolation.CreatedAt = DateTime.UtcNow;
         unitOfWork.RuleViolations.Add(ruleViolation);
     };
     pathway.Add(period);
 }
示例#28
0
        private void bAddEl_Click(object sender, EventArgs e)
        {
            int     pid = (int)pPath.Tag;
            Pathway pw  = task.GetPathwayById(pid);

            pw.elements.Add(new Element());

            ShowPanel("pElement", new object[] { pw.elements[pw.elements.Count - 1], currentPanel.Name, currentPanel.Tag, pw });
        }
示例#29
0
    private static void DrawElements(Pathway pathway, List <Vector3> path, int index)
    {
        GUIStyle style      = new GUIStyle();
        Vector3  textHeight = Vector3.up;

        style.normal.textColor = pathway.TextColor;
        style.fontSize         = pathway.TextSize;

        Handles.Label(path[index] + textHeight, index.ToString(), style);
    }
示例#30
0
    void DisablePathway(Pathway pathway, Vector2Int pos)
    {
        Block block = _template.GetBlock(pos);

        if (block == null)
        {
            return;
        }
        block.DisablePathway(pathway);
    }
示例#31
0
        private void bAddPath_Click(object sender, EventArgs e)
        {
            Pathway pw = new Pathway(new Element());

            pw.Id = GetMinPathId();
            task.Pathways.Add(pw);

            RefreshPathways();
            ShowPanel("pElement", new object[] { pw.elements[0], currentPanel.Name, currentPanel.Tag, pw });
        }
        private int HandleComponentCondition(PathwayComponentCondition input, Pathway pathway, PathwayComponent component, ref SaveStatus status)
        {
            int           newId         = 0;
            List <string> messages      = new List <string>();
            string        statusMessage = "";

            input.ParentComponentId = component.Id;
            if (pccm.Save(input, ref messages))
            {
                newId = input.Id;
                activityMgr.SiteActivityAdd(new SiteActivity()
                {
                    ActivityType     = "PathwayComponent",
                    Activity         = "Import",
                    Event            = "Add",
                    Comment          = string.Format("Added PathwayComponentCondition via Import: '{0}' for Component: '{1}'", input.Name, component.Name),
                    ActivityObjectId = newId,
                });
            }
            else
            {
                status.AddErrorRange(messages);
            }

            if (newId == 0 || (!string.IsNullOrWhiteSpace(statusMessage) && statusMessage != "successful"))
            {
                status.AddError(string.Format("Row: Issue encountered updating pathway ComponentCondition: {0} for Component: '{1}': {2}", input.Name, component.Name, statusMessage));
                return(0);
            }
            //==================================================


            //handle target components - better organization to move this to HandleComponentCondition since all components should now exist
            List <PathwayComponent> profiles = new List <PathwayComponent>();

            messages = new List <string>();
            foreach (var tc in input.HasTargetComponentList)
            {
                var targetComponent = PathwayComponentManager.Get(tc);
                if (targetComponent == null || targetComponent.Id == 0)
                {
                    //shouldn't happen here - although the add attempt could have failed?
                    status.AddError(string.Format("The target pathway component: {0} for ConditionComponent: {1} was not found. This could have been due the an issue adding the component - which should have resulted in an earlier error message.", tc, input.Name));
                    continue;
                }
                profiles.Add(targetComponent);
            }
            //now replace relationships
            if (!epcmgr.Replace(input.RowId, PathwayComponent.PathwayComponentRelationship_TargetComponent, profiles, ref status))
            {
                //status.AddErrorRange( messages );
            }

            return(newId);
        }
示例#33
0
 public Room(Rect rect, RoomArea area)
 {
     RoomRect = rect;
     OverLapRooms = new List<Room>();
     Area = area;
     isMonsterHouse = false;
     isShop = false;
     EntranceDoorPositions = new Vector2[] { };
     ID = InstanceID++;
     ConnectingPathways = new Pathway[0];
 }
示例#34
0
 public Pathway(Vector2 startpos, Vector2 endpos)
 {
     StartPosition = startpos;
     EndPosition = endpos;
     bool swap = Vector2.Distance(Vector2.zero, startpos) > Vector2.Distance(Vector2.zero, endpos);
     Vector2 sp = !swap ? startpos : endpos;
     Vector2 ep = swap ? startpos : endpos;
     int dx = (int)Mathf.Abs(ep.x - sp.x)+1;
     int dy = (int)Mathf.Abs(ep.y - sp.y)+1;
     dx += dx == 0 ? 1 : 0;
     dy += dy == 0 ? 1 : 0;
     PathwayRect = new Rect(sp, new Vector2(dx, dy));
     ConnectionRect = new Rect(PathwayRect.position-Vector2.one,PathwayRect.size+new Vector2(2,2));
     Length = (int)Vector2.Distance(sp, ep);
     ConnectingPathways = new Pathway[0];
     ConnectingRooms = new Room[0];
     //Debug.Log("L: "+Length);
 }
示例#35
0
 //This function recursively generates combinations from reversible tree nodes
 private void generateCombinations(ReversibleTreeNode input, ReversibleTreeNode output)
 {
     if (!GlobalData.isValidPathway(ReactionBitData.or(input.BitsUsed, output.BitsUsed)))
      {
     return;
      }
      if (input.Leaf)
      {
     if (output.Leaf)
     {
        Pathway combo;
        for (int i = input.Start; i < input.End; i++)
        {
           for (int o = output.Start; o < output.End; o++)
           {
              combo = new Pathway(input.Pathways[i], output.Pathways[o]);
              this.combinationsGenerated++;
              this.phaseCombinationsGenerated++;
              this.timeCombinationGeneration.Stop();
              this.timePhaseCombinationGeneration.Stop();
              this.timeBitpatternTreeBuilding.Start();
              this.timePhaseBitpatternTreeBuilding.Start();
              if (this.isExtremeRay(combo))
              {
                 this.combinations.Add(combo);
                 this.combinationsStored++;
                 this.phaseCombinationsStored++;
                 if (this.combinations.Count >= MAX_COMBINATION_LIMIT)
                 {
                    this.timeBitpatternTreeBuilding.Stop();
                    this.timePhaseBitpatternTreeBuilding.Stop();
                    this.phase++;
                 }
              }
              this.timeBitpatternTreeBuilding.Stop();
              this.timePhaseBitpatternTreeBuilding.Stop();
              this.timeCombinationGeneration.Start();
              this.timePhaseCombinationGeneration.Start();
           }
        }
     }
     else
     {
        this.generateCombinations(input, output.Node0);
        this.generateCombinations(input, output.Node1);
     }
      }
      else
      {
     if (output.Leaf)
     {
        this.generateCombinations(input.Node0, output);
        this.generateCombinations(input.Node1, output);
     }
     else
     {
        this.generateCombinations(input.Node0, output.Node0);
        this.generateCombinations(input.Node0, output.Node1);
        this.generateCombinations(input.Node1, output.Node0);
        this.generateCombinations(input.Node1, output.Node1);
     }
      }
 }
示例#36
0
 private bool isExtremeRay(Pathway p)
 {
     int columns = 0;
      for (int pr = 0, r = 0, m, pm; pr < GlobalData.numReactions; pr++, r++)
      {
     while (pr < GlobalData.numReactions && !p.ReactionBitData[pr])
     {
        pr++;
     }
     if (pr < GlobalData.numReactions)
     {
        for (m = 0, pm = GlobalData.numMetabolitesRemaining; pm < this.rankMatrix.Length; m++, pm++)
        {
           this.rankMatrix[m][r] = GlobalData.matrixS[pm][pr];
        }
        columns++;
     }
      }
      int rows = GlobalData.numInternalMetabolites - GlobalData.numMetabolitesRemaining;
      int rank = Rank.rank(this.rankMatrix, rows, columns);
      return rank == (columns - 1);
 }
示例#37
0
 //This function removes dependent pathways from the list of pathways
 private int removeDependant(Pathway[] list)
 {
     BitPatternTreeIncremental tree = new BitPatternTreeIncremental();
      int size = list.Length;
      for (int i = 0; i < size; i++)
      {
     if (!tree.addPathway(list[i]))
     {
        list[i] = list[size - 1];
        list[size - 1] = null;
        size--;
        i--;
     }
      }
      for (int i = 0; i < size; i++)
      {
     if (tree.isSuperSet(list[i]))
     {
        list[i] = list[size - 1];
        list[size - 1] = null;
        size--;
        i--;
     }
      }
      return size;
 }
示例#38
0
 public bool overlaps(Pathway pathway)
 {
     return RoomRect.Overlaps(pathway.PathwayRect, true);
 }
示例#39
0
    List<Pathway> createPathWays(RoomArea start, RoomArea end, RoomArea.Side startside, RoomArea.Side endside, RndGenerator rnd)
    {
        List<Pathway> ret = new List<Pathway>();
        Vector2 sv = start.getRoomAreaSideRandomPoint(startside, rnd);
        Vector2 ev = end.getRoomAreaSideRandomPoint(endside, rnd);
        float sx = 0, sy = 0, ex = 0, ey = 0;
        float xmin = start.RoomRect.xMin, xmax = start.RoomRect.xMax, ymin = start.RoomRect.yMin, ymax = start.RoomRect.yMax;
        int max = 0, min = 0;
        xmin++; xmax--;
        ymin++; ymax--;
        int sideline = (int)start.getSideLine(startside);
        switch (startside)
        {
            case RoomArea.Side.TOP:
                sx = rnd.Next((int)xmin, (int)xmax);
                sy = sideline-1;
                ex = sx;
                max = (int)Mathf.Max(end.Center.y, end.RoomRect.yMax, sideline + 6);
                min = sideline + 1;
                if (min >= max) max += min - max;
                ey = rnd.Next(min, max);
                break;
            case RoomArea.Side.BOTTOM:
                sx = rnd.Next((int)xmin, (int)xmax);
                sy = sideline+1;
                ex = sx;
                min = (int)Mathf.Min(end.Center.y, end.RoomRect.yMin, sideline - 6);
                min = Mathf.Max(0, min);
                max = sideline - 1;
                if (min >= max) max += min - max;
                ey = rnd.Next(min, max);
                break;
            case RoomArea.Side.LEFT:
                sy = rnd.Next((int)ymin, (int)ymax);
                ey = sy;
                sx = sideline+1;
                min = (int)Mathf.Min(end.Center.x, end.RoomRect.xMin, sideline - 6);
                min = Mathf.Max(0, min);
                max = sideline - 1;
                if (min >= max) max += min - max;
                ex = rnd.Next(min, max);
                break;
            case RoomArea.Side.RIGHT:
                sy = rnd.Next((int)ymin, (int)ymax);
                ey = sy;
                sx = sideline-1;
                max = (int)Mathf.Max(end.Center.x, end.RoomRect.xMin, sideline - 6);
                min = sideline + 1;
                if (min >= max) max += min - max;
                ex = rnd.Next(min, max);
                break;
        }
        sx = Mathf.Clamp(sx, 0, Size.x);
        ex = Mathf.Clamp(ex, 0, Size.x);
        sy = Mathf.Clamp(sy, 0, Size.y);
        ey = Mathf.Clamp(ey, 0, Size.y);
        Pathway pw = new Pathway(new Vector2(sx, sy), new Vector2(ex, ey));
        ret.Add(pw);
        int retry = 0;
        while (!end.RoomRect.Contains(pw.EndPosition)) {
            Vector2 sp = pw.EndPosition;
            Vector2 ep = Vector2.zero;
            if (pw.CurrentAxis == Pathway.Axis.HORIZONTAL)
            {
                ep = new Vector2(sp.x, end.CenterToInt.y);
            }
            else
            {
                ep = new Vector2(end.CenterToInt.x, sp.y);
            }
            pw = new Pathway(sp, ep);
            if (pw.CurrentAxis == Pathway.Axis.UNKWON) {
                if (sp.x == end.CenterToInt.x)
                {
                    ep.y = end.CenterToInt.y;
                }
                else if(sp.y == end.CenterToInt.y){
                    ep.x = end.CenterToInt.x;
                }
                pw = new Pathway(sp, ep);
            }

            //Debug.LogFormat("{0} {1} {2}", pw.ToString(), end.RoomRect.ToString(), end.RoomRect.Contains(pw.EndPosition));
            retry++;
            if (retry > 100) {
                Debug.LogFormat("Break Loop: {0} {1}", pw.ToString(),end.CenterToInt);
                break;
            }
            ret.Add(pw);
        }
        return ret;
    }
示例#40
0
    public void generatePathway(MapGraph graph)
    {
        List<Pathway> ret = new List<Pathway>();
        //Debug.Log("Edge: "+graph.EdgeList.Count);
          foreach (Edge edge in graph.EdgeList) {
            //Debug.Log("E:"+edge.ToString());
            Node start = edge.Start;
            Node end = edge.End;
            /*
            foreach (Room r in Rooms) {
                Debug.Log(start.Position +"=="+r.CenterToInt+" = "+r.CenterToInt.Equals(start.Position));
                Debug.Log(r.Position+","+r.Size);
            }
            */
            Room room1 = Rooms.Find(r => r.Area.CenterToInt.Equals(start.Position));
            Room room2 = Rooms.Find(r => r.Area.CenterToInt.Equals(end.Position));
            // startがendより右及び上に位置するとdistの各成分はマイナスになる
            Vector2 dist = (end.Position - start.Position);
            Vector2 midpos = start.Position + dist / 2;
            float angle = Mathf.Atan2(dist.x, dist.y) * Mathf.Rad2Deg;
            Vector2 norm = dist.normalized;
            Vector2 posdelta = new Vector2(Mathf.CeilToInt(norm.x), Mathf.CeilToInt(norm.y));
            //Debug.Log("S: " + start.Position + ", E:" + end.Position);
            //Debug.Log("A: " + angle + ", " + norm);

            // 2つの部屋がx,yそれぞれの軸で近接しているか判定する
            /* 近接とみなす条件
              ・ノードの中間点が境界内に含まれている場合
              境界の位置
              ・start部屋の大きさ+α
            */

            bool xproximity = (midpos.x <= room1.RoomRect.xMax + areaboderrate && midpos.x >= room1.CenterToInt.x) ||
                              (midpos.x >= room1.RoomRect.xMin - areaboderrate && midpos.x <= room1.CenterToInt.x);
            bool yproximity = (midpos.y <= room1.RoomRect.yMax + areaboderrate && midpos.y >= room1.CenterToInt.y) ||
                              (midpos.y >= room1.RoomRect.yMin - areaboderrate && midpos.y <= room1.CenterToInt.y);
            //Debug.Log("MidPos: " + midpos+", Xprox: " +xproximity+", Yprox: "+yproximity);
            Vector2[] pos = new Vector2[2];
            if (xproximity && !yproximity)
            {
                pos = getStartAndEndPosition(room1, room2, false);
            }
            else if (yproximity && !xproximity)
            {
                pos = getStartAndEndPosition(room1, room2, true);
            }
            else
            {
                if (Mathf.Abs(dist.x) < Mathf.Abs(dist.y))
                {
                    pos = getStartAndEndPosition(room1,room2,false);
                }
                else {
                    pos = getStartAndEndPosition(room1, room2, true);
                }
            }
            Pathway pw = new Pathway(pos[0],pos[1]);
            //Debug.Log("Pw: " + pw.ToString());
            if (!room2.join(pw)) {
                Vector2 dir = pw.Direction;
                //Debug.Log("Dir: "+dir);
                Vector2 sv = pw.EndPosition+dir;
                float ex = 0, ey = 0;
                if (dir.y == 0)
                {
                    ex = sv.x;
                    ey = room2.CenterToInt.y;//norm.y < 0 ? room2.RoomRect.yMax : room2.RoomRect.yMin;
                }
                else if (dir.x == 0) {
                    ey = sv.y;
                    ex = room2.CenterToInt.x; //norm.x < 0 ? room2.RoomRect.xMin : room2.RoomRect.xMax;
                }
                //sx = Mathf.Max(0, sx); sx = Mathf.Min(this.Size.x, sx);
                ex = Mathf.Max(0, ex); ex = Mathf.Min(this.Size.x, ex);
                //sy = Mathf.Max(0, sy); sy = Mathf.Min(this.Size.y, sy);
                ey = Mathf.Max(0, ey); ey = Mathf.Min(this.Size.y, ey);
                Pathway pw2 = new Pathway(sv, new Vector2(ex, ey));
                //Debug.Log("Pw2: "+pw2);
                ret.Add(pw2);
            }
            if(pw.Length != 0) ret.Add(pw);
        }
        Pathways.AddRange(ret);
    }
示例#41
0
 void drawSideWall(Pathway pw)
 {
     Rect[] sidewalls = pw.getSideWalls();
     Vector2 v1 = new Vector2(sidewalls[0].xMin, sidewalls[0].yMin); //0,0
     Vector2 v2 = new Vector2(sidewalls[0].xMax, sidewalls[0].yMin); //1,0
     Vector2 v3 = new Vector2(sidewalls[0].xMin, sidewalls[0].yMax); //0,1
     Vector2 v4 = new Vector2(sidewalls[0].xMax, sidewalls[0].yMax); //1,1
     Debug.DrawLine(v1, v2,Color.yellow);
     Debug.DrawLine(v1, v3, Color.yellow);
     Debug.DrawLine(v4, v2, Color.yellow);
     Debug.DrawLine(v4, v3, Color.yellow);
     v1 = new Vector2(sidewalls[1].xMin, sidewalls[1].yMin); //0,0
     v2 = new Vector2(sidewalls[1].xMax, sidewalls[1].yMin); //1,0
     v3 = new Vector2(sidewalls[1].xMin, sidewalls[1].yMax); //0,1
     v4 = new Vector2(sidewalls[1].xMax, sidewalls[1].yMax); //1,1
     Debug.DrawLine(v1, v2, Color.green);
     Debug.DrawLine(v1, v3, Color.green);
     Debug.DrawLine(v4, v2, Color.green);
     Debug.DrawLine(v4, v3, Color.green);
 }
示例#42
0
 //This function genreates combinations for the metabolite at given index
 private void generateCombinations(int metaboliteIndex, int inputCount, int outputCount)
 {
     //Identify input, output and non-participating pathways for the given metabolite
      Pathway[] inputs = new Pathway[inputCount];
      Pathway[] outputs = new Pathway[outputCount];
      Pathway[] nonparticipating = new Pathway[this.pathways.Length - inputCount - outputCount];
      for (int p = 0, i = 0, o = 0, n = 0; p < this.pathways.Length; p++)
      {
     if (this.pathways[p].isInput(metaboliteIndex))
     {
        inputs[i] = this.pathways[p];
        i++;
     }
     else if (this.pathways[p].isOutput(metaboliteIndex))
     {
        outputs[o] = this.pathways[p];
        o++;
     }
     else
     {
        nonparticipating[n] = this.pathways[p];
        n++;
     }
      }
      this.pathways = null;
      //Remove dependent pahtways among inputs and outputs
      inputCount = this.removeDependant(inputs);
      outputCount = this.removeDependant(outputs);
      //Create reversible trees for inputs and outputs
      ReversibleTree inputTree = new ReversibleTree(inputs, inputCount);
      ReversibleTree outputTree = new ReversibleTree(outputs, outputCount);
      GC.Collect();
      GC.WaitForPendingFinalizers();
      //Create a bitpattern tree and add efms
      this.timeCombinationGeneration.Start();
      this.timePhaseCombinationGeneration.Start();
      //Generate combinations
      this.generateCombinations(inputTree.Root, outputTree.Root);
      this.timeCombinationGeneration.Stop();
      this.timePhaseCombinationGeneration.Stop();
      GC.Collect();
      GC.WaitForPendingFinalizers();
      this.timeSupersetChecking.Start();
      this.timePhaseSupersetChecking.Start();
      //Check for supersets
      for (int i = 0; i < this.combinations.Count; i++)
      {
     this.combinationsIndependent++;
     this.phaseCombinationsIndependent++;
     this.combinations[i].updateMetaboliteCoefficients(metaboliteIndex);
     if (this.combinations[i].isEFM())
     {
        this.efms.Add(this.combinations[i]);
        this.combinations[i] = this.combinations[this.combinations.Count - 1];
        this.combinations[this.combinations.Count - 1] = null;
        this.combinations.RemoveAt(this.combinations.Count - 1);
        i--;
     }
      }
      //Update bitpattern tree statistics
      this.timeSupersetChecking.Stop();
      this.timePhaseSupersetChecking.Stop();
      this.treeHeight = 0;
      this.bucketCount = 0;
      if (this.maxTreeHeight < this.treeHeight)
      {
     this.maxTreeHeight = this.treeHeight;
      }
      if (this.maxBucketCount < this.bucketCount)
      {
     this.maxBucketCount = this.bucketCount;
      }
      //Update list of pathways in the network
      this.pathways = new Pathway[nonparticipating.Length + this.combinations.Count];
      for (int i = 0; i < nonparticipating.Length; i++)
      {
     this.pathways[i] = nonparticipating[i];
      }
      for (int i = nonparticipating.Length, c = 0; i < this.pathways.Length; i++, c++)
      {
     this.pathways[i] = this.combinations[c];
     this.combinations[c] = null;
      }
      this.combinations.Clear();
 }
示例#43
0
 public bool join(Pathway pathway)
 {
     if (this.overlaps(pathway)) return true;
     Vector2 start = pathway.StartPosition;
     Vector2 end = pathway.EndPosition;
     return RoomRect.Contains(start + dirdelta[0]) || RoomRect.Contains(start + dirdelta[1]) ||
            RoomRect.Contains(start - dirdelta[0]) || RoomRect.Contains(start - dirdelta[1]) ||
            RoomRect.Contains(end + dirdelta[0]) || RoomRect.Contains(end + dirdelta[1]) ||
            RoomRect.Contains(end - dirdelta[0]) || RoomRect.Contains(end - dirdelta[1]);
 }
示例#44
0
 public bool isConnectedPathway(Pathway pw)
 {
     if (pw == null) return false;
     if (ConnectingPathways.Length == 0) return false;
     return Array.Find(ConnectingPathways, p => p.Equals(pw)) != null;
 }
示例#45
0
 //Constructor
 //Arguement pathways represents reactions in the network
 public EFMGenerator(Pathway[] pathways)
 {
     this.pathways = pathways;
      this.efms = new List<Pathway>(100000);
      this.combinations = new List<Pathway>(MAX_COMBINATION_LIMIT);
      this.timeMetaboliteRemvoed = new Stopwatch();
      this.timeBitpatternTreeBuilding = new Stopwatch();
      this.timeCombinationGeneration = new Stopwatch();
      this.timeSupersetChecking = new Stopwatch();
      this.timePhaseMetaboliteRemvoed = new Stopwatch();
      this.timePhaseBitpatternTreeBuilding = new Stopwatch();
      this.timePhaseCombinationGeneration = new Stopwatch();
      this.timePhaseSupersetChecking = new Stopwatch();
      this.rankMatrix = new double[GlobalData.matrixS.Length][];
      for (int m = 0; m < this.rankMatrix.Length; m++)
      {
     this.rankMatrix[m] = new double[GlobalData.numReactions];
      }
 }