protected void NotifyObservers(Observation observation, object data = null) { foreach (var i in _observers[observation]) { i.Value(this, data); } }
public static void PushFor(string key, Observation glue) { if (registerInstance.For(key) != null) { foreach (Observer observer in registerInstance.For(key)) { foreach (Observation observation in observer.GetObservations()) { Push(observation, glue); } } } }
public static bool AddObservation(int idPatient, Observation obs) { ServiceObservationClient serviceObs = new ServiceObservationClient(); try { return serviceObs.AddObservation(idPatient, obs); } catch (Exception) { return false; } }
public void ApplyObservations(Observation[] observations) { // Go through all inputs foreach (InputNeuron iNeuron in rules.Inputs) { // Deactivate them iNeuron.IsInputActive = false; // Look if any observation matches their input patterns foreach (Observation obs in observations) { if (obs.FitsNeuron(iNeuron)) { iNeuron.IsInputActive = true; break; } } } }
public static void Push(Observation observation, Observation glue) { try { if (observation != null) { byte[] bytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(observation)); using (FileStream fw = File.Create(@"c:\temp\observations\observation_" + DateTime.Now.Ticks)) { fw.Write(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(observation)), 0, bytes.Length); } using (StreamWriter fw = File.AppendText(@"c:\temp\observations\rolling.txt")) { fw.Write(JsonConvert.SerializeObject(observation) + Environment.NewLine); } } } catch (Exception) { } }
public async Task GivenAResourceWithSearchUrlReference_WhenPostResourceAndIdentifierExists_ThenServerShouldReturnSuccess() { var observation = Samples.GetDefaultObservation().ToPoco <Observation>(); var patient = Samples.GetDefaultPatient().ToPoco <Patient>(); var uniqueIdentifier = Guid.NewGuid().ToString(); patient.Identifier.First().Value = uniqueIdentifier; // Create patient resource await _client.CreateAsync(patient); observation.Subject.Reference = $"Patient?identifier={uniqueIdentifier}"; using FhirResponse <Observation> createResponse = await _client.CreateAsync( observation); Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode); Observation createdResource = createResponse.Resource; Assert.NotNull(createdResource); Assert.NotNull(createdResource.Id); }
public async Task GivenAUserWithHardDeletePermissions_WhenHardDeletingAResource_TheServerShouldReturnSuccess() { FhirClient tempClient = Client.CreateClientForUser(TestUsers.ReadWriteUser, TestApplications.NativeClient); Observation createdResource = await tempClient.CreateAsync(Samples.GetDefaultObservation().ToPoco <Observation>()); tempClient = Client.CreateClientForUser(TestUsers.AdminUser, TestApplications.NativeClient); // Hard-delete the resource. await tempClient.HardDeleteAsync(createdResource); tempClient = Client.CreateClientForUser(TestUsers.ReadOnlyUser, TestApplications.NativeClient); // Getting the resource should result in NotFound. await ExecuteAndValidateNotFoundStatus(() => tempClient.ReadAsync <Observation>(ResourceType.Observation, createdResource.Id)); async Task <FhirException> ExecuteAndValidateNotFoundStatus(Func <Task> action) { FhirException exception = await Assert.ThrowsAsync <FhirException>(action); Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode); return(exception); } }
public CompositeSearchTestFixture(DataStore dataStore, Format format) : base(dataStore, format) { var resultDictionary = new Dictionary <string, Observation>(TestFileNames.Length); for (int i = 0; i < TestFileNames.Length; i++) { string testFileName = TestFileNames[i]; Observation result = FhirClient.CreateResourcesAsync <Observation>(() => { Observation observation = Samples.GetJsonSample <Observation>(testFileName); observation.Identifier.Add(new Identifier(null, TestSessionId)); return(observation); }).Result; resultDictionary.Add(testFileName, result); } Observations = resultDictionary; }
public static CdaCodeObservation CreateFamilyHistoryObservation(Observation observation) { CdaCodeObservation returnVal = CreateCodeObservation(observation); if (returnVal != null) { returnVal.TemplateIds = new CdaTemplateIdList( FamilyHistoryObservationTemplateId, SimpleObservationTemplateId, CcdFamilyHistoryObservationTemplateId ); returnVal.Relationship = observation.Relationship; // *** All the family observations from OB H&P Initial are diagnoses *** returnVal.Code = new CdaCode() { CodeSystem = CodingSystem.SnomedCT, Code = "282291009", DisplayName = "Diagnosis" }; } return(returnVal); }
public void TestDecimalPrecisionSerializationInJson() { var dec6 = 6m; var dec60 = 6.0m; var ext = new FhirDecimal(dec6); var obs = new Observation(); obs.AddExtension("http://example.org/DecimalPrecision", ext); var json = FhirJsonSerializer.SerializeToString(obs); var obs2 = FhirJsonParser.Parse <Observation>(json); Assert.AreEqual("6", ((FhirDecimal)obs2.GetExtension("http://example.org/DecimalPrecision").Value).Value.Value.ToString(CultureInfo.InvariantCulture)); ext = new FhirDecimal(dec60); obs = new Observation(); obs.AddExtension("http://example.org/DecimalPrecision", ext); json = FhirJsonSerializer.SerializeToString(obs); obs2 = FhirJsonParser.Parse <Observation>(json); Assert.AreEqual("6.0", ((FhirDecimal)obs2.GetExtension("http://example.org/DecimalPrecision").Value).Value.Value.ToString(CultureInfo.InvariantCulture)); }
public async Task GivenAUserWithUpdatePermissions_WhenUpdatingAResource_TheServerShouldReturnSuccess() { TestFhirClient tempClient = _client.CreateClientForUser(TestUsers.AdminUser, TestApplications.NativeClient); Observation createdResource = await tempClient.CreateAsync(Samples.GetDefaultObservation().ToPoco <Observation>()); tempClient = _client.CreateClientForUser(TestUsers.ReadWriteUser, TestApplications.NativeClient); createdResource.Text = new Narrative { Status = Narrative.NarrativeStatus.Generated, Div = "<div>Updated resource content</div>", }; using FhirResponse <Observation> updateResponse = await tempClient.UpdateAsync(createdResource); Assert.Equal(HttpStatusCode.OK, updateResponse.StatusCode); Observation updatedResource = updateResponse.Resource; Assert.NotNull(updatedResource); Assert.Equal(createdResource.Id, updatedResource.Id); Assert.NotEqual(createdResource.Meta.VersionId, updatedResource.Meta.VersionId); Assert.NotEqual(createdResource.Meta.LastUpdated, updatedResource.Meta.LastUpdated); }
private List <Observation> GetInvalidRightSideParameterObservations(Observation leftSideObservation, List <Observation> observations, List <Rule> rules) { var invalidObservations = new List <Observation>(); foreach (var rule in rules) { var rightSideParamObservations = observations.Where(obs => rule.RightParam == obs.ObservedProperty.CustomId).ToList(); if (!rightSideParamObservations.Any()) { continue; } var invalidObservationsThisRule = rightSideParamObservations.Where( rightObs => !IsObservationValid(leftSideObservation, rule, rightObs)); invalidObservations.AddRange(invalidObservationsThisRule); } return(invalidObservations); }
public static List <Observation> CreateOutcomeObservations(string patientDfn, PregnancyOutcomeType outcomeType, string outcomeDate, string pregIen) { List <Observation> returnList = new List <Observation>(); Observation obs = new Observation() { PatientDfn = patientDfn, Category = OutcomeCategory, PregnancyIen = pregIen, Code = OutcomeTypeCode, CodeSystem = CDA.Common.CodingSystem.Other, //Observation.OtherCodeSystem, EntryDate = DateTime.Now, //.ToString(VistaDates.VistADateFormatFour), Description = "Pregnancy Outcome", Value = outcomeType.ToString() }; returnList.Add(obs); if ((outcomeType == PregnancyOutcomeType.FullTermDelivery) || (outcomeType == PregnancyOutcomeType.PretermDelivery)) { obs = new Observation() { PatientDfn = patientDfn, Category = OutcomeCategory, PregnancyIen = pregIen, Code = "75092-7", CodeSystem = CodingSystem.Loinc, //Observation.LoincCodeSystem, EntryDate = DateTime.Now, //.ToString(VistaDates.VistADateFormatFour), Description = "Birth Date of Fetus", Value = outcomeDate }; returnList.Add(obs); } return(returnList); }
internal static Observation ToFhirInternal(BloodPressure bp, Observation observation) { if (bp.IrregularHeartbeatDetected.HasValue) { observation.AddExtension(HealthVaultVocabularies.IrregularHeartBeatExtensionName, new FhirBoolean(bp.IrregularHeartbeatDetected.Value)); } var diastolicComponent = new Observation.ComponentComponent { Code = HealthVaultVocabularies.GenerateCodeableConcept(HealthVaultVitalStatisticsCodes.BloodPressureDiastolic), Value = new Quantity((decimal)bp.Diastolic, UnitAbbreviations.MillimeterOfMecury) }; var systolicComponent = new Observation.ComponentComponent { Code = HealthVaultVocabularies.GenerateCodeableConcept(HealthVaultVitalStatisticsCodes.BloodPressureSystolic), Value = new Quantity((decimal)bp.Systolic, UnitAbbreviations.MillimeterOfMecury) }; observation.Component = new List <Observation.ComponentComponent> { diastolicComponent, systolicComponent }; if (bp.Pulse != null) { observation.Component.Add(new Observation.ComponentComponent { Code = HealthVaultVocabularies.GenerateCodeableConcept(HealthVaultVitalStatisticsCodes.HeartRate), Value = new Quantity((decimal)bp.Pulse, UnitAbbreviations.PerMinute) }); } observation.Effective = new FhirDateTime(bp.When.ToLocalDateTime().ToDateTimeUnspecified()); observation.Code = HealthVaultVocabularies.BloodPressure; return(observation); }
private void Interpret(Planning.HighLevelProgramExecution.Program program) { if (!Final(program)) { do { //Console.WriteLine(program.GetType()); string message = ReceiveMessage(); Console.WriteLine("Receive message: {0}", message); if (message == "observation") { string observationName = ReceiveMessage(); Console.WriteLine("Receive observation: {0}", observationName); Observation observation = _observationDict[observationName]; _mentalAttitude.Update(observation); int memory = CUDD.ReadMemoryInUse(); Console.WriteLine("Used memory: {0}MB", memory >> 20); } else { //Console.WriteLine(program); program = Trans(program); int memory = CUDD.ReadMemoryInUse(); Console.WriteLine("Used memory: {0}MB", memory >> 20); if (!Final(program)) { SendMessage("remain"); } else { SendMessage("quit"); break; } } } while (true); } }
private List <Observation> UrinalysisObservations(Customer customer, Event theEventData) { ITestResultRepository testResultRepository = new UrineMicroalbuminTestRepository(); var isNewResultFlow = theEventData.EventDate >= _settings.ResultFlowChangeDate; var testResult = (UrineMicroalbuminTestResult)testResultRepository.GetTestResults(customer.CustomerId, theEventData.Id, isNewResultFlow); var observation = new List <Observation>(); if (testResult != null && (testResult.TestNotPerformed == null || testResult.TestNotPerformed.TestNotPerformedReasonId <= 0) && (testResult.UnableScreenReason == null || testResult.UnableScreenReason.Count == 0)) { if (testResult.MicroalbuminValue != null) { var refRang = string.Empty; var reading = testResult.MicroalbuminValue != null ? testResult.MicroalbuminValue.Reading != null?testResult.MicroalbuminValue.Reading.ToString() : "" : ""; if (testResult.Finding != null) { refRang = testResult.Finding.Label; } var urinalysis = new Observation { Id = ClinicalDocumentHelper.ClinicalRoots.First(cr => cr.FirstValue == ClinicalRootType.Urinalysis).SecondValue, TemplateId = new[] { ClinicalDocumentHelper.ClinicalRoots.First(cr => cr.FirstValue == ClinicalRootType.Urinalysis).SecondValue }, Code = ClinicalDocumentHelper.LoincCodes.First(x => x.FirstValue == LoincCode.Urinalysis).SecondValue, Reference = " <referenceRange><observationRange><text>" + refRang + "</text></observationRange></referenceRange>", StatusCode = new StatusCode { Code = "completed" }, ObservationValue = new ObservationValue { Value = reading, Unit = "" } }; observation.Add(urinalysis); } } return(observation); }
public static void RunTest() { ModelObservationCreator cc = new ModelObservationCreator(); List <Observation> a = cc.ReadObsModelFiles("111.txt", "111_obs.txt"); Observation bObservation = a[0]; List <Gate> allComponents = bObservation.TheModel.Components; // 11 , 22 , 33 // 44 , 22 , 55 Conflict c1 = new Conflict(new List <Gate>() { allComponents[0], allComponents[2], allComponents[3] }); Conflict c2 = new Conflict(new List <Gate>() { allComponents[1], allComponents[2], allComponents[4] }); ConflictSet cs = new ConflictSet(); cs.Conflicts = new List <Conflict>() { c1, c2 }; MicC_Diagnosis minCDiagnosis = A_MinCAlgorithm.FindMinC(cs); foreach (Gate g in minCDiagnosis.TheDiagnosis) { Console.WriteLine("Gate = " + g.Id); } Console.WriteLine("A_MinC Unit test 1. minc = " + minCDiagnosis.cardinality); int x = 0; }
public async Task GivenABundleWithInvalidConditionalReferenceInResourceBody_WhenSubmittingATransaction_ThenProperOperationOutComeIsReturned() { string patientId = Guid.NewGuid().ToString(); var observation = new Observation { Subject = new ResourceReference { Reference = "Patient?identifier=http:/example.org/fhir/ids|" + patientId, }, }; var bundle = new Bundle { Type = BundleType.Transaction, Entry = new List <EntryComponent> { new EntryComponent { Resource = observation, Request = new RequestComponent { Method = HTTPVerb.POST, Url = "Observation", }, }, }, }; using var fhirException = await Assert.ThrowsAsync <FhirException>(async () => await _client.PostBundleAsync(bundle)); Assert.Equal(HttpStatusCode.BadRequest, fhirException.StatusCode); string[] expectedDiagnostics = { "Given conditional reference 'Patient?identifier=http:/example.org/fhir/ids|" + patientId + "' does not resolve to a resource." }; IssueType[] expectedCodeType = { IssueType.Invalid }; ValidateOperationOutcome(expectedDiagnostics, expectedCodeType, fhirException.OperationOutcome); }
public void NoModObservationTest() { Observation o = new Observation(); o.Identifier.Add(new Identifier("a", "b")); o.Status = ObservationStatus.Cancelled; o.Code = new CodeableConcept("codeSystem", "codeCode", "codeDisplay", "codeText"); NoModObservation n = NoModObservation.Create(o); { Assert.True(n.Status.Get(out Code <ObservationStatus> status) == true); Assert.True(status.Value == ObservationStatus.Cancelled); n.Status.Set(new Code <ObservationStatus>(ObservationStatus.Final)); Assert.True(n.Status.Get(out status) == true); Assert.True(status.Value == ObservationStatus.Final); } { Assert.True(n.Identifier.Count == 1); Assert.True(n.Identifier.Get(0, out Identifier value) == true); Assert.True(value.System == "a"); n.Identifier.Add(new Identifier("c", "d")); Assert.True(n.Identifier.Count == 2); Assert.True(n.Identifier.Get(1, out value) == true); Assert.True(value.System == "c"); Assert.True(value.Value == "d"); } { Assert.True(n.Code.Get(out CodeableConcept coding) == true); Assert.True(coding.Coding.Count == 1); Assert.True(coding.Coding[0].System == "codeSystem"); Assert.True(coding.Coding[0].Code == "codeCode"); Assert.True(coding.Coding[0].Display == "codeDisplay"); } }
public async Task AddExplorationPointsForNewObservation(Observation observation) { // 1 point pour l'ajout d'un relevé var currentDate = DateTime.UtcNow; var pointHistory = new List <PointHistory>(); pointHistory.Add(new PointHistory { Point = 1, Type = (int)ExplorationPoint.CreateObservation, Date = currentDate }); if (observation.Pictures != null && observation.Pictures.Count > 0) { //2 points pour une photos pointHistory.Add(new PointHistory { Point = 2, Type = (int)ExplorationPoint.TakePictureTree, Date = currentDate }); } if (!string.IsNullOrEmpty(observation.ObservationStatements[0].SpeciesName) || !string.IsNullOrEmpty(observation.ObservationStatements[0].CommonSpeciesName)) { //6 points pour le nom de l'espèce pointHistory.Add(new PointHistory { Point = 6, Type = (int)ExplorationPoint.CompleteSpecies, Date = currentDate }); } if (!string.IsNullOrEmpty(observation.ObservationStatements[0].Genus) || !string.IsNullOrEmpty(observation.ObservationStatements[0].CommonGenus)) { //3 points pour le genre de l'espèce pointHistory.Add(new PointHistory { Point = 3, Type = (int)ExplorationPoint.CompleteGenus, Date = currentDate }); } await this.UsersManager.AddExplorationPoints(observation.UserId, pointHistory); await this.UsersManager.AddTitles(observation.UserId); }
public async Task WhenUpdatingANewResource_GivenTheResource_TheServerShouldReturnTheNewResourceSuccessfully() { var resourceToCreate = Samples.GetDefaultObservation(); resourceToCreate.Id = Guid.NewGuid().ToString(); FhirResponse <Observation> createResponse = await Client.UpdateAsync(resourceToCreate); Assert.Equal(System.Net.HttpStatusCode.Created, createResponse.StatusCode); Observation createdResource = createResponse.Resource; Assert.NotNull(createdResource); Assert.Equal(resourceToCreate.Id, createdResource.Id); Assert.NotNull(createdResource.Meta.VersionId); Assert.NotNull(createdResource.Meta.LastUpdated); Assert.NotNull(createResponse.Headers.ETag); Assert.NotNull(createResponse.Headers.Location); Assert.NotNull(createResponse.Content.Headers.LastModified); Assert.Contains(createdResource.Meta.VersionId, createResponse.Headers.ETag.Tag); TestHelper.AssertLocationHeaderIsCorrect(Client, createdResource, createResponse.Headers.Location); TestHelper.AssertLastUpdatedAndLastModifiedAreEqual(createdResource.Meta.LastUpdated, createResponse.Content.Headers.LastModified); }
public ActionResult Create(Observation model, HttpPostedFileBase file) { //Extra complex validation is performed within the service to method, //then the model state validity is used. Observation observation = UnitOfWork.ObservationService.Add( new ModelStateWrapper(ModelState), model, file); if (observation != null) { //Email if specified if (!string.IsNullOrWhiteSpace(observation.Email)) { var observationsMailer = new ObservationsMailer(); observationsMailer.Details(observation).Send(); } return(RedirectToAction("Thanks")); } PopulateViewBag(); return(View(model)); }
public async void GivenOneEntryAfterContinuationToken_ReadOneFromBundleWithContinuationAsync_ThenResourceIsReturned_Test() { var bundle = new Bundle(); bundle.Entry = new List <Bundle.EntryComponent>(); bundle.Link = new List <Bundle.LinkComponent>(); var continuationBundle = new Bundle(); continuationBundle.Entry = new List <Bundle.EntryComponent>(); continuationBundle.Link = new List <Bundle.LinkComponent>(); var observation = new Observation(); var entry = new Bundle.EntryComponent(); entry.Resource = observation; continuationBundle.Entry.Add(entry); var client = Substitute.For <IFhirClient>(); client.ContinueAsync(Arg.Any <Bundle>()).Returns(ret => System.Threading.Tasks.Task.FromResult(continuationBundle), ret => System.Threading.Tasks.Task.FromResult <Bundle>(null)); Assert.Equal(observation, await bundle.ReadOneFromBundleWithContinuationAsync <Observation>(client)); }
public async Task GivenATransactionBundleWithIdentifierReferences_WhenResolved_ThenReferencesValuesAreNotUpdated() { var observation = new Observation { Subject = new ResourceReference { Identifier = new Identifier("https://example.com", "12345"), }, }; var bundle = new Hl7.Fhir.Model.Bundle { Entry = new List <EntryComponent> { new EntryComponent { Resource = observation, }, }, }; var referenceIdDictionary = new Dictionary <string, (string resourceId, string resourceType)>(); foreach (var entry in bundle.Entry) { var references = entry.Resource.GetAllChildren <ResourceReference>().ToList(); // Asserting the conditional reference value before resolution Assert.Null(references.First().Reference); var requestUrl = (entry.Request != null) ? entry.Request.Url : null; await _testBaseConditionalHandler.ResolveReferencesAsync(entry.Resource, referenceIdDictionary, requestUrl, CancellationToken.None); // Asserting the resolved reference value after resolution Assert.Null(references.First().Reference); } }
public Observation AddNewObservationAndLogInfo(int id, ILogger <ObservationsController> _logger) { var bird = Birds.FirstOrDefault(b => b.Id == id); if (bird == null) { throw new InvalidOperationException("Bad request, wrong bird's id"); } // for only this assignment purpose, to be improved when working with real database var observations = Birds.SelectMany(b => b.Observations); var maxObservationId = 0; if (observations.Count() > 0) { maxObservationId = observations.Max(o => o.Id); } var newObservationId = ++maxObservationId; var newObservation = new Observation(Id: newObservationId, BirdName: bird.BirdName); var birdNeeded = Birds.FirstOrDefault(b => b.BirdName == newObservation.BirdName); if (birdNeeded == null) { throw new InvalidDataException("Something wrong with data file"); } birdNeeded.Observations.Add(newObservation); var jsonData = JsonConvert.SerializeObject(Birds, Formatting.Indented); File.WriteAllText(path, jsonData); logNewObservationInfo(newObservation, _logger); return(newObservation); }
public ActionResult DeleteConfirmed(Observation model) { ResultModel result = new ResultModel(); try { #region Service資料庫 this._observationService.Delete(model); #endregion #region 息頁面設定 result.Status = true; result.Message = "MessageComplete".ToLocalized(); #endregion } catch (Exception ex) { #region 錯誤時錯誤訊息 result.Status = false; result.Message = ex.Message.ToString(); #endregion } return(Json(result)); }
public int ManageObservationDetails(Observation Ob) { try { SqlParameter[] sqlparam; sqlparam = new SqlParameter[11]; sqlparam[0] = new SqlParameter("@Id", Ob.Id); sqlparam[1] = new SqlParameter("@PhysicalExamination", Ob.PhysicalExamination); sqlparam[2] = new SqlParameter("@Since", Ob.Since); sqlparam[3] = new SqlParameter("@Period", Ob.Period); sqlparam[4] = new SqlParameter("@Diagnosis", Ob.Diagnosis); sqlparam[5] = new SqlParameter("@Complaint", Ob.Complaints); sqlparam[6] = new SqlParameter("@CasePaperNo", Ob.CasePaperNo); sqlparam[7] = new SqlParameter("@HospitalId", Ob.HospitalId); sqlparam[8] = new SqlParameter("@PatientId", Ob.PatientId); sqlparam[9] = new SqlParameter("@CreatedBy", Ob.CreatedBy); sqlparam[10] = new SqlParameter("@QueueId", Ob.QueueId); return(CommonFunction.Save("USP_Prec_Observation", sqlparam, "")); } catch (Exception) { throw; } }
/// <summary> /// Generic private method for creating observations /// </summary> /// <param name="patientId"></param> /// <param name="observation"></param> /// <param name="timeStamp"></param> /// <param name="seqNumber"></param> /// <param name="status"></param> /// <returns></returns> private Observation CreateObservation(string patientId, ObservationBase observation, DateTimeOffset timeStamp, int seqNumber = 1, ObservationStatus status = ObservationStatus.Final) { Observation hb = new Observation() { Id = observation.Id }; hb.Code = new CodeableConcept(observation.System, observation.Code, observation.Name); hb.Value = new Quantity(observation.Value, observation.Unit); hb.Subject = new ResourceReference($"{_fhirOptions.Endpoint}/Patient/{patientId}"); //hb.Subject = new ResourceReference($"urn:uuid:{patientId}"); hb.Identifier.Add(new Identifier("http://acme.org/sequence-nos", seqNumber.ToString())); hb.Effective = new FhirDateTime(timeStamp); hb.Status = status; // Optionally add the category hb.Category.Add(new CodeableConcept("http://terminology.hl7.org/CodeSystem/observation-category", "laboratory", "Laboratory")); return(hb); }
public ActionResult EditObservation(string id, string type, string patientID) { //POŁĄCZENIE Z KLIENTEM var client = new FhirClient("http://localhost:8080/baseR4"); client.PreferredFormat = ResourceFormat.Json; ViewBag.ID = patientID; if (type == "Observation") { //POBRANIE DANYCH O OBSERWACJI Observation observation = client.Read <Observation>("Observation/" + id); EditObservation myObservation = new EditObservation(); //PRZEKAZANIE DO EDYCJI myObservation.Reason = observation.Code.Text; myObservation.ID = observation.Id; myObservation.Status = observation.Status; return(View(myObservation)); } ViewBag.Message = "Some Error until Redirect"; return(View()); }
private void obsSearchButton_Click(object sender, EventArgs e) { obsSearchStatus.Text = "Searching..."; var endpoint = new Uri("http://fhirtest.uhn.ca/baseDstu2"); var client = new FhirClient(endpoint); var query = new string[] { "subject=Patient/" + obsSearchPatient.Text }; Bundle result = client.Search <Observation>(query); obsSearchStatus.Text = "Got " + result.Entry.Count() + " records!"; obsFinderId.Text = ""; obsFinderValue.Text = ""; foreach (var entry in result.Entry) { Observation obs = (Observation)entry.Resource; String name = "Unknown"; if (obs.Code != null) { name = obs.Code.Text; } if (obs.Value is SampledData) { obsFinderId.Text = obsFinderId.Text + name + "\r\n"; obsFinderValue.Text = obsFinderValue.Text + ((SampledData)obs.Value).Data.ToString() + "\r\n"; } else if (obs.Value is Quantity) { obsFinderId.Text = obsFinderId.Text + obs.Code.Coding[0] + "\r\n"; obsFinderValue.Text = obsFinderValue.Text + ((Quantity)obs.Value).Value.ToString() + "\r\n"; } } }
public async Task <List <BloodPressureRecord> > FetchBloodPressure(string id) { var q = new SearchParams().Where("patient=" + id).Where("code=55284-4").OrderBy("-date"); q.Count = 5; Bundle result = await _client.SearchAsync <Observation>(q); var bloodPressureRecords = new List <BloodPressureRecord>(); if (result.Total > 0) { List <Bundle.EntryComponent> entryList = result.Entry; foreach (var entry in entryList) { Observation o = (Observation)entry.Resource; bloodPressureRecords.Add(new BloodPressureRecord() { DiastolicValue = ((Quantity)o.Component[0].Value).Value.ToString(), SystolicValue = ((Quantity)o.Component[1].Value).Value.ToString(), Date = DateTime.Parse(o.Issued.ToFhirDateTime()).ToString("dd/MM/yyyy HH:mm") }); } ; } else { bloodPressureRecords.Add(item: new BloodPressureRecord() { DiastolicValue = "0", SystolicValue = "0", Date = "" }); } return(bloodPressureRecords); }
public async Task GivenVariousTypesOfResources_WhenSearchingAcrossAllResourceTypes_ThenOnlyResourcesMatchingTypeParameterShouldBeReturned() { // Create various resources. Patient[] patients = await Client.CreateResourcesAsync <Patient>(3); Observation observation = (await Client.CreateAsync(Samples.GetDefaultObservation())).Resource; Organization organization = (await Client.CreateAsync(Samples.GetDefaultOrganization())).Resource; Bundle bundle = await Client.SearchAsync("?_type=Patient"); ValidateBundle(bundle, patients); bundle = await Client.SearchPostAsync(null, ("_type", "Patient")); ValidateBundle(bundle, patients); bundle = await Client.SearchAsync("?_type=Observation,Patient"); Assert.True(bundle.Entry.Count > patients.Length); bundle = await Client.SearchPostAsync(null, ("_type", "Patient,Observation")); Assert.True(bundle.Entry.Count > patients.Length); bundle = await Client.SearchAsync($"?_type=Observation,Patient&_id={observation.Id}"); ValidateBundle(bundle, observation); bundle = await Client.SearchPostAsync(null, ("_type", "Patient,Observation"), ("_id", observation.Id)); ValidateBundle(bundle, observation); bundle = await Client.SearchAsync($"?_type=Observation,Patient&_id={organization.Id}"); ValidateBundle(bundle); bundle = await Client.SearchPostAsync(null, ("_type", "Patient,Observation"), ("_id", organization.Id)); ValidateBundle(bundle); }
internal static void AddHR(object Item, string SType) { using (var db = new DatabaseContext()) { switch (SType) { case "Attack": Attack tempA = new Attack(); foreach (PropertyInfo x in Item.GetType().GetProperties()) { x.SetValue(tempA, x.GetValue(Item)); } db.HelicopterRotorcraft.Add(tempA); break; case "Observation": Observation tempO = new Observation(); foreach (PropertyInfo x in Item.GetType().GetProperties()) { x.SetValue(tempO, x.GetValue(Item)); } db.HelicopterRotorcraft.Add(tempO); break; case "Utility": Utility tempU = new Utility(); foreach (PropertyInfo x in Item.GetType().GetProperties()) { x.SetValue(tempU, x.GetValue(Item)); } db.HelicopterRotorcraft.Add(tempU); break; } db.SaveChanges(); } }
void InitOp(ParallelLineOperation op) { // The direction is significant only if an offset distance // has been specified. m_IsLeft = false; // Pick up the offset. Observation offset = op.Offset; // If it's an observed distance, get the side. Distance dist = (offset as Distance); if (dist != null) { m_Offset = new Distance(dist); m_IsLeft = m_Offset.SetPositive(); } else { // The only other thing it could be is an offset point. OffsetPoint offPoint = (offset as OffsetPoint); if (offPoint != null) { m_Point = offPoint.Point; } } if (m_Point != null) { SelectPoint(m_Point); } else if (m_Offset != null) { offsetTextBox.Text = m_Offset.Format(); } }
public DomainResource GetDataWithResource(FhirClient fhirClient) { Observation observation = new Observation { Status = ObservationStatus.Final, Code = new CodeableConcept("http://loinc.org", "29463-7", "Body weight"), Value = new Quantity(new decimal(130.00), "kg") { Code = "kg" }, DataAbsentReason = new CodeableConcept("http://hl7.org/fhir/data-absent-reason", "unknown"), Category = new List <CodeableConcept> { new CodeableConcept("http://hl7.org/fhir/observation-category", "vital-signs", "Vital Signs") }, Subject = new ResourceReference("Patient/example"), Effective = new FhirDateTime(DateTime.Now), Meta = new Meta { Profile = new[] { "http://hl7.org/fhir/StructureDefinition/vitalsigns" } } }; return(fhirClient.Create(observation)); }
/// <summary> /// Initializes a new instance of the <see cref="IntersectDirectionAndDistanceOperation"/> class /// using the data read from persistent storage. /// </summary> /// <param name="editDeserializer">The mechanism for reading back content.</param> internal IntersectDirectionAndDistanceOperation(EditDeserializer editDeserializer) : base(editDeserializer) { m_Direction = editDeserializer.ReadPersistent<Direction>(DataField.Direction); m_Distance = editDeserializer.ReadPersistent<Observation>(DataField.Distance); m_From = editDeserializer.ReadFeatureRef<PointFeature>(this, DataField.From); m_Default = editDeserializer.ReadBool(DataField.Default); FeatureStub to = editDeserializer.ReadPersistent<FeatureStub>(DataField.To); FeatureStub dirLine = editDeserializer.ReadPersistentOrNull<FeatureStub>(DataField.DirLine); FeatureStub distLine = editDeserializer.ReadPersistentOrNull<FeatureStub>(DataField.DistLine); DeserializationFactory dff = new DeserializationFactory(this); dff.AddFeatureStub(DataField.To, to); dff.AddFeatureStub(DataField.DirLine, dirLine); dff.AddFeatureStub(DataField.DistLine, distLine); ProcessFeatures(dff); }
/// <summary> /// Exchanges update items that were previously generated via /// a call to <see cref="GetUpdateItems"/>. /// </summary> /// <param name="data">The update data to apply to the edit (modified to /// hold the values that were previously defined for the edit)</param> public override void ExchangeData(UpdateItemCollection data) { m_Direction = data.ExchangeObservation<Direction>(this, DataField.Direction, m_Direction); m_Distance = data.ExchangeObservation<Observation>(this, DataField.Distance, m_Distance); m_From = data.ExchangeFeature<PointFeature>(this, DataField.From, m_From); m_Default = data.ExchangeValue<bool>(DataField.Default, m_Default); AssignObservedLengths(); }
/// <summary> /// Initializes a new instance of the <see cref="IntersectDirectionAndDistanceOperation"/> class /// </summary> /// <param name="dir">Direction observation.</param> /// <param name="dist">Distance observation.</param> /// <param name="from">The point the distance was observed from.</param> /// <param name="usedefault">True if the default intersection is required (the one /// closer to the origin of the direction line). False for the other one (if any).</param> internal IntersectDirectionAndDistanceOperation(Direction dir, Observation dist, PointFeature from, bool useDefault) : base() { m_Direction = dir; m_Distance = dist; m_From = from; m_Default = useDefault; }
/// <summary> /// Calculates the intersection point. /// </summary> /// <param name="dir">Direction observation.</param> /// <param name="dist">Distance observation.</param> /// <param name="from">The point the distance was observed from.</param> /// <param name="usedefault">True if the default intersection is required (the one /// closer to the origin of the direction line). False for the other one (if any).</param> /// <returns>The position of the intersection (null if it cannot be calculated).</returns> IPosition Calculate(Direction dir, Observation distance, PointFeature from, bool usedefault) { // Call the static function that is also used by the dialog. IPosition xsect, x1, x2; if (Calculate(dir, distance, from, usedefault, out xsect, out x1, out x2)) return xsect; else return null; }
/// <summary> /// Initializes a new instance of the <see cref="RadialOperation"/> class. /// </summary> /// <param name="dir">The direction (could contain an offset).</param> /// <param name="length">The length of the sideshot arm (either a <see cref="Distance"/> or /// an <see cref="OffsetPoint"/>).</param> internal RadialOperation(Direction dir, Observation length) : base() { m_Direction = dir; m_Length = length; }
/// <summary> /// Creates a <c>NewCircleForm</c> for a circle, based on a previously /// defined circle. /// </summary> /// <param name="cmd">The command creating this dialog</param> /// <param name="recall">The editing operation that's being recalled (null /// if not doing a recall)</param> internal NewCircleForm(CommandUI cmd, Operation recall) { InitializeComponent(); m_Cmd = cmd; m_Recall = (NewCircleOperation)recall; m_Center = null; m_Radius = null; m_Circle = null; m_RadiusPoint = null; m_RadiusDistance = null; m_Focus = null; }
private static Organizer MakeOrganizer() { Organizer o = new Organizer(); o.ClassCode = new CS<x_ActClassDocumentEntryOrganizer>(x_ActClassDocumentEntryOrganizer.BATTERY); o.TemplateId = new LIST<II>(); o.TemplateId.Add(new II("2.16.840.1.113883.10.20.22.4.1")); o.Id = new SET<II>(new II(new Guid())); o.Code = new CD<string>( "11579-0", "2.16.840.1.113883.6.1", "LOINC", null, "Thyrotropin [Units/volume] in Serum or Plasma by Detection limit less than or equal to 0.05 mIU/L", null); o.StatusCode = new CS<ActStatus>(ActStatus.Completed); Observation obs = new Observation(); //It automatically adds class code obs.MoodCode = new CS<x_ActMoodDocumentObservation>(x_ActMoodDocumentObservation.Eventoccurrence); obs.TemplateId = new LIST<II>(); obs.TemplateId.Add(new II("2.16.840.1.113883.10.20.22.4.2")); obs.Id = new SET<II>(new II(new Guid())); obs.Code = new CD<string>( "3016-3", "2.16.840.1.113883.6.1", "LOINC", null, "Thyrotropin [Units/volume] in Serum or Plasma", null); obs.Text = new ED(); obs.Text.Reference = new TEL("#result1"); obs.StatusCode = new CS<ActStatus>(ActStatus.Completed); obs.EffectiveTime = new IVL<TS>(); obs.EffectiveTime.Value = new TS(DateTime.Today); obs.Value = new PQ(6m, "mIU/L"); obs.InterpretationCode = new SET<CE<string>>(); obs.InterpretationCode.Add( new CE<string>( "A", "2.16.840.1.113883.5.83", "ObservationInterpretation", null, "abnormal", null)); obs.InterpretationCode.Add( new CE<string>( "H", "2.16.840.1.113883.5.83", "ObservationInterpretation", null, "high", null)); obs.ReferenceRange = new List<ReferenceRange>(); obs.ReferenceRange.Add(new ReferenceRange( new ObservationRange( null, new ED("normal: 0.29–5.11 mIU/L"), null, null))); Component4 comp = new Component4(); comp.SetClinicalStatement(obs); o.Component = new List<Component4>(); o.Component.Add(comp); return o; }
/// <summary> /// Calculates the intersection point. /// </summary> /// <param name="dir">Direction observation.</param> /// <param name="distance">Distance observation.</param> /// <param name="from">The point the distance was observed from.</param> /// <param name="usedefault">True if the default intersection is required (the one /// closer to the origin of the direction line). False for the other one (if any).</param> /// <param name="xsect">The position of the intersection (if any).</param> /// <param name="xsect1">The 1st choice intersection (if any).</param> /// <param name="xsect2">The 2nd choice intersection (if any).</param> /// <returns>True if intersections were calculated. False if the distance circles /// don't intersect.</returns> internal static bool Calculate(Direction dir, Observation distance, PointFeature from, bool usedefault, out IPosition xsect, out IPosition xsect1, out IPosition xsect2) { // Initialize intersection positions. xsect = xsect1 = xsect2 = null; // Get the distance. double dist = distance.GetDistance(from).Meters; if (dist < Constants.TINY) return false; // Form circle with a radius that matches the observed distance. ICircleGeometry circle = new CircleGeometry(from, dist); // See if there is actually an intersection between the direction & the circle. IPosition x1, x2; uint nx = dir.Intersect(circle, out x1, out x2); if (nx==0) return false; // If we have 2 intersections, and we need the non-default one, pick up the 2nd // intersection. If only 1 intersection, use that, regardless of the setting for // the "use default" flag. if (nx==2 && !usedefault) xsect = x2; else xsect = x1; // Return if the distance is an offset point. OffsetPoint offset = (distance as OffsetPoint); if (offset!=null) { xsect1 = x1; xsect2 = x2; return true; } // Reduce observed distance to the mapping plane. ISpatialSystem sys = CadastralMapModel.Current.SpatialSystem; dist = dist * sys.GetLineScaleFactor(from, xsect); // And calculate the exact intersection (like above)... // Form circle with a radius that matches the reduced distance. ICircleGeometry circlep = new CircleGeometry(from, dist); // See if there is actually an intersection between the direction & the circle. nx = dir.Intersect(circlep, out x1, out x2); if (nx==0) return false; // If we have 2 intersections, and we need the non-default one, pick up the 2nd // intersection. If only 1 intersection, use that, regardless of the setting for // the "use default" flag. if (nx==2 && !usedefault) xsect = x2; else xsect = x1; xsect1 = x1; xsect2 = x2; return true; }
string LoggerToObs(string loggerfile) { progressBar1.Value = 0; lObserv.Items.Clear(); //прописываем основные строки string refStr1 = "[CHAOS] - Observing object \""; string refStr2 = "[CHAOS] - Pointing started: RA ="; //string refStr2="[Agate/BKU] - Fine pointing complete"; string refStr3 = "'AGATE LIMB DEC',"; string refStr4 = "'AGATE LIMB HA',"; string refStr5 = "'AGATE LIMB TIME',"; //string refStr6="[CHAOS] - RA ="; string refStr7 = "[CHAOS] - Orientation:"; string refStr8 = "[logger] - Exposure complete."; string refStr9 = "[logger] - 127.0.0.1> grab(1,'"; StreamReader sr = new StreamReader(loggerfile); String line; Observation Obs = new Observation(); System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("ru-RU"); line = sr.ReadLine(); int count = 1; while (line != null) { if (line.IndexOf(refStr1) != -1) { Obs = new Observation(); int pos1 = line.IndexOf("\"", 54); string name = line.Substring(54, pos1 - 54); Obs.Object = name; count = 2; } if ((line.IndexOf(refStr2) != -1) && (count == 2)) { int pos2 = line.IndexOf("\"", 59); string name = line.Substring(59, pos2 - 59); Obs.Pos = name; Obs.Error1 = 0; count = 3; } if ((line.IndexOf(refStr3) != -1) && (count == 3)) { int pos2 = line.IndexOf(")", 72); string name = line.Substring(72, pos2 - 72); name = name.Replace('.', ','); name = name.Replace(".", ci.NumberFormat.NumberDecimalSeparator); name = name.Replace(",", ci.NumberFormat.NumberDecimalSeparator); Obs.LimbD = Convert.ToDouble(name); count = 4; } if ((line.IndexOf(refStr4) != -1) && (count == 4)) { int pos2 = line.IndexOf(")", 71); string name = line.Substring(71, pos2 - 71); name = name.Replace('.', ','); name = name.Replace(".", ci.NumberFormat.NumberDecimalSeparator); name = name.Replace(",", ci.NumberFormat.NumberDecimalSeparator); Obs.LimbA = Convert.ToDouble(name); count = 5; } if ((line.IndexOf(refStr5) != -1) && (count == 5)) { int pos2 = line.IndexOf(")", 73); string name = line.Substring(73, pos2 - 74); Obs.Time = name; pos2 = line.IndexOf(' ', 0); name = line.Substring(0, pos2); Obs.Date = name; count = 7; } /*if ((line.IndexOf(refStr6)!=-1)&&(count==6)) { int pos2=line.IndexOf("\"",43); string name=line.Substring(43,pos2-43); Obs.Pos=name; count=7; }*/ if ((line.IndexOf(refStr7) != -1) && (count == 7)) { char nname = line[51]; if (nname == '0') Obs.Orientation = 2; else Obs.Orientation = 1; count = 9; } if ((line.IndexOf(refStr8) != -1) && (count == 8)) { Obs.Error2 = 0; count = 9; } if ((line.IndexOf(refStr9) != -1) && (count == 9)) { int pos2 = line.IndexOf("'", 56); string name = line.Substring(56, pos2 - 56); Obs.File = name; //if ((Obs.Error1==0)&&(Obs.Error2==0)) //{ Obs.Dir = loggerfile.Substring(0,loggerfile.LastIndexOf('\\'))+'\\'; Obs.AddtoObs(lObserv); //} count = 1; } //Obs.AddtoObs(lOrient); //lOrient.Items.Add(line); //progressBar1.Value += line.Length; line = sr.ReadLine(); } progressBar1.Value = progressBar1.Maximum; sr.Close(); string fobsnew = "dl_" + loggerfile.Substring(loggerfile.LastIndexOf('\\') + 1, loggerfile.Length - loggerfile.LastIndexOf('\\') - 1) + ".obs"; StreamWriter sr2 = new StreamWriter(fobsnew); for (int i = 0; i < lObserv.Items.Count; i++) { sr2.WriteLine(lObserv.Items[i].ToString()); } sr2.Close(); return fobsnew; }
private static void WriteObservation(Observation observation, StringBuilder reportBuilder) { var indentation = new string(' ', 8); reportBuilder.AppendFormat( "{0}- {1}{2}", indentation, observation, Environment.NewLine); }
private static Observation MakeObservation(string section) { Observation o = new Observation(); if (section == "ALLERGIES") { //It automatically adds class code o.MoodCode = new CS<x_ActMoodDocumentObservation>(x_ActMoodDocumentObservation.Eventoccurrence); o.TemplateId = new LIST<II>(); o.TemplateId.Add(new II("2.16.840.1.113883.10.20.22.4.7")); o.Id = new SET<II>(new II(new Guid())); o.Code = new CD<string>( "ASSERTION", "2.16.840.1.113883.5.4", null, null, null, null); o.StatusCode = new CS<ActStatus>(ActStatus.Completed); o.EffectiveTime = new IVL<TS>(new TS()); o.EffectiveTime.Low = new TS(DateTime.Now); o.EffectiveTime.Low.NullFlavor = new CS<NullFlavor>(NullFlavor.Unknown); o.Value = new CD<string>( "416098002", "2.16.840.1.113883.6.96", "SNOMED CT", null, "drug allergy", new ED(new TEL("#allergy1"))); Participant2 participant2 = new Participant2(); participant2.TypeCode = new CS<ParticipationType>(ParticipationType.Consumable); participant2.ParticipantRole = new ParticipantRole(); participant2.ParticipantRole.ClassCode = new CS<string>("MANU"); PlayingEntity pe = new PlayingEntity(null, new CE<string>("70618", "2.16.840.1.113883.6.88", "RxNorm", null, "Penicillin", null), null, null, null); pe.Code.OriginalText = new ED(); pe.Code.OriginalText.Reference = new TEL("#allergy1"); pe.ClassCode = new CS<EntityClassRoot>(new EntityClassRoot()); participant2.ParticipantRole.SetPlayingEntityChoice(pe); o.Participant.Add(participant2); o.EntryRelationship = new List<EntryRelationship>(); EntryRelationship er = new EntryRelationship(); er.TypeCode = new CS<x_ActRelationshipEntryRelationship>(x_ActRelationshipEntryRelationship.MFST); er.InversionInd = new BL(true); Observation obs = new Observation(); obs.MoodCode = new CS<x_ActMoodDocumentObservation>(x_ActMoodDocumentObservation.Eventoccurrence); obs.TemplateId = new LIST<II>(); obs.TemplateId.Add(new II("2.16.840.1.113883.10.20.22.4.8")); obs.Code = new CD<string>("SEV", "2.16.840.1.113883.5.4", "ActCode", null, null, null); obs.Text = new ED(); obs.Text.Reference = new TEL("#allergy1"); obs.StatusCode = new CS<ActStatus>(); obs.StatusCode.Code = new MARC.Everest.DataTypes.Primitives.CodeValue<ActStatus>(ActStatus.Completed); obs.Value = new CD<string>( "6736007", "2.16.840.1.113883.6.96", "SNOMED CT", null, "moderate", null); er.SetClinicalStatement(obs); o.EntryRelationship.Add(er); } if (section == "SOCIAL HISTORY") { //It automatically adds class code o.MoodCode = new CS<x_ActMoodDocumentObservation>(x_ActMoodDocumentObservation.Eventoccurrence); o.TemplateId = new LIST<II>(); o.TemplateId.Add(new II("2.16.840.1.113883.10.20.22.4.78")); o.Id = new SET<II>(new II(new Guid())); o.Code = new CD<string>( "ASSERTION", "2.16.840.1.113883.5.4", null, null, null, null); o.StatusCode = new CS<ActStatus>(ActStatus.Completed); o.EffectiveTime = new IVL<TS>(new TS(DateTime.Now), new TS(DateTime.Now)); o.Value = new CD<string>( "8517006", "2.16.840.1.113883.6.96", "SNOMED CT", null, "former smoker", null); } if (section == "PROBLEM LIST") { //It automatically adds class code o.MoodCode = new CS<x_ActMoodDocumentObservation>(x_ActMoodDocumentObservation.Eventoccurrence); o.TemplateId = new LIST<II>(); o.TemplateId.Add(new II("2.16.840.1.113883.10.20.22.4.4")); o.Id = new SET<II>(new II(new Guid())); o.Code = new CD<string>( "64572001", "2.16.840.1.113883.6.96", "SNOMED CT", null, "Condition", null); o.Text = new ED(); o.Text.Reference = new TEL("#problem1"); o.StatusCode = new CS<ActStatus>(ActStatus.Completed); o.EffectiveTime = new IVL<TS>(new TS(DateTime.Now), null); o.Value = new CD<string>( "5962100", "2.16.840.1.113883.6.96", "SNOMED CT", null, "Essential Hypertension", null); } return o; }
/// <summary> /// Projects Enumeration of Observations from the raw set of Observation entities. /// During build: /// override the observations start date using the start date of the corresponding observation period. /// </summary> /// <param name="observations">raw set of observations entities</param> /// <param name="visitOccurrences">the visit occurrences entities for current person</param> /// <param name="observationPeriods">the observation periods entities for current person</param> /// <returns>Enumeration of Observation from the raw set of Observation entities</returns> public override IEnumerable<Observation> BuildObservations(Observation[] observations, Dictionary<long, VisitOccurrence> visitOccurrences, ObservationPeriod[] observationPeriods) { if (observationPeriods.Length != 0) { var unique = new HashSet<Observation>(); foreach (var observation in observations) { if (observation.ConceptId == -999) continue; observation.StartDate = observationPeriods[0].StartDate; observation.ValueAsConceptId = Convert.ToInt32(observation.UnitsConceptId); observation.UnitsConceptId = null; observation.UnitsSourceValue = null; unique.Add(observation); } foreach (var observation in unique) { yield return observation; } } }
/// <summary> /// Obtains update items for a revised version of this edit /// (for later use with <see cref="ExchangeData"/>). /// </summary> /// <param name="dist1">1st distance observation.</param> /// <param name="from1">The point the 1st distance was observed from.</param> /// <param name="dist2">2nd distance observation.</param> /// <param name="from2">The point the 2nd distance was observed from.</param> /// <param name="isdefault">True if the default intersection is required (the one that has the /// lowest bearing with respect to the 2 from points). False for the other one (if any).</param> /// <returns>The items representing the change (may be subsequently supplied to /// the <see cref="ExchangeUpdateItems"/> method).</returns> internal UpdateItemCollection GetUpdateItems(Direction dir, Observation distance, PointFeature from, bool isdefault) { UpdateItemCollection result = new UpdateItemCollection(); result.AddObservation<Direction>(DataField.Direction, m_Direction, dir); result.AddObservation<Observation>(DataField.Distance, m_Distance, distance); result.AddFeature<PointFeature>(DataField.From, m_From, from); result.AddItem<bool>(DataField.Default, m_Default, isdefault); return result; }
/// <summary> /// Intersects this direction with a specific entity type. /// </summary> /// <param name="ent">The entity type to look for.</param> /// <param name="maxdist">Observation defining the maximum distance between the /// direction's from-point & the intersection. This can either be a <c>Distance</c> /// or an <c>OffsetPoint</c> object.</param> /// <param name="xsect">The position of the intersection (if any). Null if no intersection found.</param> /// <returns>True if an intersection was found.</returns> bool Intersect(IEntity ent, Observation maxdist, out IPosition xsect) { // Initialize the intersection. xsect = null; // Get the max distance. It has to be defined to be SOMETHING. double dist = maxdist.GetDistance(this.From).Meters; if (Math.Abs(dist) < Constants.TINY) return false; // Define the position of the direction line. IPosition from = this.StartPosition; IPosition to = Geom.Polar(from, this.Bearing.Radians, dist); throw new NotImplementedException("Direction.Intersect"); /* // Construct a corresponding line segment. CeLocation start(vfrom); CeLocation end(vto); CeSegment seg(start,end); // Intersect the segment with the map (all features on // the currently active theme). CeLayerList curlayer; CeXObject xseg(seg,&curlayer); // Get the first intersection (if any) with the specified // entity type. UINT4 nprim = xseg.GetCount(); // How many primitives did we intersect? FLOAT8 bestdsq = 10e+38; // Closest distance (squared) so far. FLOAT8 tdistsq; // Test distance (squared). LOGICAL gotone=FALSE; for ( UINT4 i=0; i<nprim; i++ ) { // Get the next thing we intersected. const CeXResult& xres = xseg[i]; const CeLine* const pLine = dynamic_cast<const CeLine* const>(xres.GetpObject()); // Skip if it wasn't a line. if ( !pLine ) continue; // Find the attached arc that has the current theme. Has // to be topological(?) const CeArc* const pArc = pLine->GetpArc(curlayer); // Skip if it doesn't have the desired entity type. if ( pArc && pArc->GetpEntity()!=&ent ) continue; // Determine the intersection on the primitive that is // closest to the start of the direction (ignoring any // intersections that are right at the start of the // direction line). gotone = TRUE; UINT4 nx = xres.GetCount(); CeVertex vtest; for ( UINT4 j=0; j<nx; j++ ) { vtest = xres.GetX1(j); tdistsq = vfrom.DistanceSquared(vtest); if ( tdistsq<bestdsq && tdistsq>TINY ) { xsect = vtest; bestdsq = tdistsq; } // Check any grazing intersection too. if ( xres.IsGrazing() ) { vtest = xres.GetX2(j); tdistsq = vfrom.DistanceSquared(vtest); if ( tdistsq<bestdsq && tdistsq>TINY ) { xsect = vtest; bestdsq = tdistsq; } } } // next intersection } // next intersected primitive return gotone; } // end of Intersect */ }
/// <summary> /// Reads data that was previously written using <see cref="WriteData"/> /// </summary> /// <param name="editDeserializer">The mechanism for reading back content.</param> /// <param name="center">Point at the center of the circle.</param> /// <param name="radius">The radius of the circle.</param> /// <param name="arc">The arc running around the circumference of the circle</param> /// <param name="closingPoint">The closing point of the circle (if it was created by this edit). Null /// if the radius was specified using an offset point.</param> static void ReadData(EditDeserializer editDeserializer, out PointFeature center, out Observation radius, out FeatureStub closingPoint, out FeatureStub arc) { center = editDeserializer.ReadFeatureRef<PointFeature>(DataField.Center); radius = editDeserializer.ReadPersistent<Observation>(DataField.Radius); closingPoint = editDeserializer.ReadPersistentOrNull<FeatureStub>(DataField.ClosingPoint); arc = editDeserializer.ReadPersistent<FeatureStub>(DataField.Arc); }
public void Unregister(Observation observation, object observer) { Action<Observable, object> action; _observers[observation].TryRemove(observer, out action); }
/// <summary> /// Initializes a new instance of the <see cref="RadialOperation"/> class /// using the data read from persistent storage. /// </summary> /// <param name="editDeserializer">The mechanism for reading back content.</param> internal RadialOperation(EditDeserializer editDeserializer) : base(editDeserializer) { m_Direction = editDeserializer.ReadPersistent<Direction>(DataField.Direction); m_Length = editDeserializer.ReadPersistent<Observation>(DataField.Length); DeserializationFactory dff = new DeserializationFactory(this); dff.AddFeatureStub(DataField.To, editDeserializer.ReadPersistent<FeatureStub>(DataField.To)); dff.AddFeatureStub(DataField.Line, editDeserializer.ReadPersistentOrNull<FeatureStub>(DataField.Line)); ProcessFeatures(dff); }
/// <summary> /// Corrects this operation. /// </summary> /// <param name="center">The point at the center of the circle.</param> /// <param name="radius">The radius of the circle (either a <see cref="Distance"/> object, /// or an <see cref="OffsetPoint"/> that sits on the circumference of the circle.</param> /// <returns>True if operation updated ok.</returns> internal bool Correct(PointFeature center, Observation radius) { throw new NotImplementedException(); /* // If the center point has changed, cut the reference to this // operation from the old point, and change it so the // operation is referenced from the new center. if (!Object.ReferenceEquals(m_Center, center)) { m_Center.CutOp(this); m_Center = center; m_Center.AddOp(this); } // If the old radius observation refers to an offset point, cut // the reference that the point has to this op. If nothing has // changed, the reference will be re-inserted when the // observation is re-saved below. CutOffsetRef(m_Radius); // Get rid of the previously defined observation, and replace // with the new one (we can't necessarily change the old one // because we may have changed the type of observation). m_Radius.OnRollback(this); m_Radius = radius; m_Radius.AddReferences(this); return true; */ }
// creates the array that makes decisions for the state machine //Dummy method for making a bayesian decision protected void makeDecision() { // find the closest enemy to dragon Vector3 minDistVec = new Vector3(100000000000,0,0); // store the closest EnemyBehavior closestToDrag = null; foreach (EnemyBehavior e in manager.enemies) { if ((transform.position - e.transform.position).sqrMagnitude < (transform.position - minDistVec).sqrMagnitude) { closestToDrag = e; minDistVec = e.transform.position; } } //if (closestToDrag != null) target = closestToDrag.transform; float closestEnemyDistanceToDragon = (transform.position - closestToDrag.transform.position).magnitude; EnemyBehavior closest = (EnemyBehavior)manager.enemies[0]; minDistVec = new Vector3(1.0f, 0.0f, 0.0f) * 40.0f; // find clsoest to tower foreach (EnemyBehavior e in manager.enemies) { if ((tower.position - e.transform.position).sqrMagnitude < (tower.position - closest.transform.position).sqrMagnitude) { closest = e; minDistVec = e.transform.position; } } float closestEnemyDistanceToTower = (tower.position - minDistVec).magnitude; // get info about world // find how many dudes are "near" the closest dude int enemiesNearDragonEnemy = 0; foreach (EnemyBehavior e in manager.enemies) { if ((closestToDrag.transform.position - e.transform.position).sqrMagnitude < 300) { enemiesNearDragonEnemy++; } } int enemiesNearTowerEnemy = 0; foreach (EnemyBehavior e in manager.enemies) { if ((closest.transform.position - e.transform.position).sqrMagnitude < 300) { enemiesNearTowerEnemy++; } } float distToTower = Vector3.Distance (transform.position, tower.position); //brain.Decide(/*closest to dragon, numbydragon, closest to tower, num by tower*/); bool goHome = brain.Decide( closestEnemyDistanceToDragon, enemiesNearDragonEnemy, closestEnemyDistanceToTower, enemiesNearTowerEnemy, distToTower); //print (goHome); // save this decision for (var i=3; i>-1; i--) { if (i < 3) lastFourDecisions [i + 1] = lastFourDecisions [i]; if (i == 0) { lastFourDecisions [0] = new Observation (); lastFourDecisions[0].closestToDragon = closestEnemyDistanceToDragon; lastFourDecisions[0].numByDragon = enemiesNearDragonEnemy; lastFourDecisions[0].closestToTower = closestEnemyDistanceToTower; lastFourDecisions[0].numByTower = enemiesNearTowerEnemy; lastFourDecisions[0].dragonDistFromTower = distToTower; lastFourDecisions[0].chooseTargetClosestToTowerGood = goHome; } } //now dragon decides which enemy to pursue -- if true, enemy closest to tower //-- if false, enemy closest to dragon if (goHome) { target = closest.transform;} else { target = closestToDrag.transform;} //update the HUD to reflect dragon's decision player.GetComponent<CommandControls>().UpdateHUD(goHome ? 1 : 2); //tell me you've made a decision UnityEngine.Debug.Log("Made a new decision after " + timeSinceDecision); }
/// <summary> /// Initializes a new instance of the <see cref="NewCircleOperation"/> class /// </summary> /// <param name="center">The point at the center of the circle.</param> /// <param name="radius">The radius of the circle (either a <see cref="Distance"/> object, /// or an <see cref="OffsetPoint"/> that sits on the circumference of the circle.</param> internal NewCircleOperation(PointFeature center, Observation radius) : base() { m_Center = center; m_Radius = radius; }
/// <summary> /// Calculates the position of the sideshot point. /// </summary> /// <param name="dir">The direction observation (if any).</param> /// <param name="len">The length observation (if any). Could be a <c>Distance</c> or an /// <c>OffsetPoint</c>.</param> /// <returns>The position of the sideshot point (null if there is insufficient data /// to calculate a position)</returns> internal static IPosition Calculate(Direction dir, Observation len) { // Return if there is insufficient data. if (dir == null || len == null) return null; // Get the position of the point the sideshot should radiate from. PointFeature from = dir.From; // Get the position of the start of the direction line (which may be offset). IPosition start = dir.StartPosition; // Get the bearing of the direction. double bearing = dir.Bearing.Radians; // Get the length of the sideshot arm. double length = len.GetDistance(from).Meters; // Calculate the resultant position. Note that the length is the length along the // bearing -- if an offset was specified, the actual length of the line from-to = // sqrt(offset*offset + length*length) IPosition to = Geom.Polar(start, bearing, length); // Return if the length is an offset point. In that case, the length we have obtained // is already a length on the mapping plane, so no further reduction should be done // (although it's debateable). if (len is OffsetPoint) return to; // Using the position we've just got, reduce the length we used to a length on the // mapping plane (it's actually a length on the ground). ISpatialSystem sys = CadastralMapModel.Current.SpatialSystem; double sfac = sys.GetLineScaleFactor(start, to); return Geom.Polar(start, bearing, length * sfac); }
/// <summary> /// Uses the currently displayed information to try to construct a /// circle object. /// </summary> /// <returns>The constructed circle (null if a circle cannot be created /// based on the information that's currently displayed)</returns> Circle GetCurrentCircle() { Circle result = null; // Get rid of any previous radius observation. m_Radius = null; if (m_Center!=null && (m_RadiusPoint!=null || m_RadiusDistance!=null)) { double radius; // If we have an offset point, get the radius. if (m_RadiusPoint!=null) radius = Geom.Distance(m_Center, m_RadiusPoint); else radius = m_RadiusDistance.Meters; // Create the circle result = new Circle(m_Center, radius); // Create the appropriate distance observation. // (not sure why these were needed, it certainly looks out of place as // part of this method) if (m_RadiusPoint!=null) m_Radius = new OffsetPoint(m_RadiusPoint); else m_Radius = new Distance(m_RadiusDistance); } return result; }
/// <summary> /// Obtains update items for a revised version of this edit /// (for later use with <see cref="ExchangeData"/>). /// </summary> /// <param name="dir">The direction (could contain an offset).</param> /// <param name="length">The length of the sideshot arm (either a <see cref="Distance"/> /// or an <see cref="OffsetPoint"/>).</param> /// <returns>The items representing the change (may be subsequently supplied to /// the <see cref="ExchangeUpdateItems"/> method).</returns> internal UpdateItemCollection GetUpdateItems(Direction dir, Observation length) { UpdateItemCollection result = new UpdateItemCollection(); result.AddObservation<Direction>(DataField.Direction, m_Direction, dir); result.AddObservation<Observation>(DataField.Length, m_Length, length); return result; }
public void Register(Observation observation, object observer, Action<Observable, object> action) { _observers[observation].TryAdd(observer, action); }
/// <summary> /// Exchanges update items that were previously generated via /// a call to <see cref="GetUpdateItems"/>. /// </summary> /// <param name="data">The update data to apply to the edit (modified to /// hold the values that were previously defined for the edit)</param> public override void ExchangeData(UpdateItemCollection data) { m_Direction = data.ExchangeObservation<Direction>(this, DataField.Direction, m_Direction); m_Length = data.ExchangeObservation<Observation>(this, DataField.Length, m_Length); if (m_Line != null) m_Line.ObservedLength = (m_Length as Distance); }