/// <summary> /// Writes all experiment graph attributes. /// </summary> /// <param name="writer">The writer.</param> /// <param name="flow">The flow.</param> public virtual void WriteGraphAttributes(XmlWriter writer, IExperiment flow) { string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()); System.IO.Directory.CreateDirectory(path); PropertyDescriptorCollection propertiesToWrite = TypeDescriptor.GetProperties(flow); foreach (PropertyDescriptor property in propertiesToWrite) { WriteXmlAttribute(writer, property, flow); } writer.WriteStartElement("References"); { if (flow.References != null) { var serializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(PackageSystem.PackageReference), null); foreach (IPackageReference reference in flow.References) { serializer.Serialize(writer, reference); } } } writer.WriteEndElement(); // Iterate again and write any elements that are pending. ALL attributes must be done first, or it results in invalid XML foreach (PropertyDescriptor property in propertiesToWrite) { WriteXmlElement(writer, property, flow); } }
public TwoD_Density_Base(IExperiment exp, Plane dir, double plane_pos) : base(exp.Temperature) { this.exp = exp; this.pos_z = plane_pos; this.plane = Plane.yz; // Get nx and ny dimensions depending on the orientation if (plane == Plane.xy) { this.dx = exp.Dx_Dens; this.dy = exp.Dy_Dens; this.xmin = exp.Xmin_Dens; this.ymin = exp.Ymin_Dens; this.nx = exp.Nx_Dens; this.ny = exp.Ny_Dens; } else if (plane == Plane.yz) { this.dx = exp.Dy_Dens; this.dy = exp.Dz_Dens; this.xmin = exp.Ymin_Dens; this.ymin = exp.Zmin_Dens; this.nx = exp.Ny_Dens; this.ny = exp.Nz_Dens; } else if (plane == Plane.zx) { this.dx = exp.Dz_Dens; this.dy = exp.Dx_Dens; this.xmin = exp.Zmin_Dens; this.ymin = exp.Xmin_Dens; this.nx = exp.Nz_Dens; this.ny = exp.Nx_Dens; } else { throw new NotImplementedException(); } }
public async Task <IEnumerable <MathErrorOutcome> > DoExperiment(IExperiment experiment) { if (!(experiment.ExperimentPositions?.Any() ?? false)) { throw new Exception("No Experiment Positions generated."); } if (!IsDataSetCalculated) { throw new ApplicationException("DataSet is not calculated"); } if (!IsANFISTrained) { throw new ApplicationException("ANFIS is not trained"); } var mathematicalOutcomes = new List <IKinematicOutcome>(); var anfisOutcomes = new List <IKinematicOutcome>(); experiment.ExperimentPositions.ToList().ForEach(point => { var anfisOut = CalculateAngelsUsingANFIS(point).GetAwaiter().GetResult(); var mathOuts = CalculateArmJoint(point).GetAwaiter().GetResult() .Select(x => new KinematicOutcome(x.Theta1.ConvertRadiansToDegrees(), x.Theta2.ConvertRadiansToDegrees(), x.JointPosition)); var mathOut = mathOuts.OrderBy(x => x, new CustomSort(anfisOut)).FirstOrDefault(); anfisOutcomes.Add(anfisOut); mathematicalOutcomes.Add(mathOut); }); experiment.SetActualOutputs(mathematicalOutcomes); experiment.SetAnfisOutputs(anfisOutcomes); return(await experiment.CalculateError()); }
void on_cmd_startNoiseDefR(object sender, RoutedEventArgs e) { if (experiment != null) { experiment.Dispose(); } var calPath = string.Format("{0}\\{1}", AppDomain.CurrentDomain.BaseDirectory, "NoiseCalibration"); var amplifierNoiseFilePath = string.Format("{0}\\{1}", calPath, "AmplifierNoise.dat"); var frequencyResponseFilePath = string.Format("{0}\\{1}", calPath, "FrequencyResponse.dat"); var amplifierNoise = ReadCalibrationFile(amplifierNoiseFilePath); var frequencyResponse = ReadCalibrationFile(frequencyResponseFilePath); var motorDriver = new SerialDevice("COM5", 115200, Parity.None, 8, StopBits.One); IMotionController1D motor = new SA_2036U012V(motorDriver) as IMotionController1D; experiment = new Noise_DefinedResistance(((measurementInterface as Noise_at_DefinedResistance).DataContext as Noise_DefinedResistanceModel).ExperimentSettings.AgilentU2542AResName, motor, amplifierNoise, frequencyResponse); experiment.DataArrived += Noise_at_der_R_DataArrived; experiment.Status += experimentStatus; experiment.Progress += experimentProgress; if (measurementInterface != null) { if (measurementInterface is Noise_at_DefinedResistance) { experiment.Start(((measurementInterface as Noise_at_DefinedResistance).DataContext as Noise_DefinedResistanceModel).ExperimentSettings); } } }
public OneD_ThomasFermiSolver(IExperiment exp, double dz, double zmin, int nz) : base(exp) { this.dz = dz; this.zmin = zmin; this.nz = nz; }
void cmdStartIV_at_defR_Click(object sender, RoutedEventArgs e) { // Has to be implemented in another section of code var smuDriver = new VisaDevice("GPIB0::26::INSTR") as IDeviceIO; var keithley = new Keithley26xxB <Keithley2602B>(smuDriver); var smu = keithley[Keithley26xxB_Channels.Channel_A]; var motorDriver = new SerialDevice("COM1", 115200, Parity.None, 8, StopBits.One); var motor = new SA_2036U012V(motorDriver) as IMotionController1D; experiment = new IV_DefinedResistance(smu, motor) as IExperiment; experiment.DataArrived += experimentIV_at_def_R_DataArrived; experiment.Status += experimentStatus; experiment.Progress += experimentProgress; if (measurementInterface != null) { if (measurementInterface is IV_at_DefinedResistance) { experiment.Start(((measurementInterface as IV_at_DefinedResistance).DataContext as IV_DefinedResistanceModel).ExperimentSettigns); } } }
/// <summary> /// Associate available cameras with automation and setup class /// Connect camera to LightField /// </summary> /// <param name="experiment"></param> /// <returns></returns> private void AddAvailableCameras() { // Add available camera foreach (var camera in experiment_.AvailableDevices) { if (experiment_.AvailableDevices.Count > 0 && camera.Type == DeviceType.Camera) { experiment_ = new OpenLightField(this, visibleLightField: true).Experiment; // Connect camera to LightField experiment_.Add(camera); string cameraName = string.Format("Model: {0}, SN: {1}", camera.Model, camera.SerialNumber); // Assign background worker, identity, etc.. // through camera setup class CameraSetup cameraSetup = new CameraSetup(experiment_, this, cameraName); experiment_ = cameraSetup.Experiment; } } }
/// <summary> /// Validates the entire experiment. /// It validates the structure of the experimental graph, /// validates all inputs and outputs, /// checks if all components are in the component library. /// </summary> /// <param name="experiment">The experiment.</param> /// <param name="vertices">The vertices, that has been parsed from the start node. Nodes that are not connected to the start are being skipped.</param> /// <param name="edges">The edges, that has been parsed from the start node.</param> /// <returns> /// true if there is no errors, false, if errors has been detected /// </returns> public static bool ValidateExperiment(IExperiment experiment, out List <ExperimentNode> vertices, out List <ExperimentNodeConnection> edges, List <string> workspaceTypesDirectories, bool validateInputMapping, LoggerNameRoot loggerNameRoot) { bool noErrors = GraphValidator.Validate(experiment, out vertices, out edges); if (noErrors) { var availableInputMappingsPerNode = new TraceLab.Core.Utilities.InputMappings(experiment); if (validateInputMapping) { noErrors = InputMappingValidator.Validate(experiment, availableInputMappingsPerNode); } if (noErrors) { //recompile all decisions noErrors = TraceLab.Core.Decisions.DecisionCompilationRunner.CompileAllDecisionNodes(experiment, availableInputMappingsPerNode, workspaceTypesDirectories, loggerNameRoot); } } if (noErrors) { noErrors = ValidComponents(vertices); } return(noErrors); }
/// <summary> /// Compiles all decision nodes code and loops code in the given experiment /// </summary> /// <param name="experiment">The experiment.</param> /// <param name="availableInputMappingsPerNode">The available input mappings per node.</param> /// <param name="workspaceTypesDirectories">The workspace types directories.</param> /// <param name="loggerNameRoot">The logger name root.</param> /// <returns> /// true if there were no errors, otherwise false /// </returns> public static bool CompileAllDecisionNodes(IExperiment experiment, InputMappings availableInputMappingsPerNode, List <string> workspaceTypesDirectories, LoggerNameRoot loggerNameRoot) { bool noErrors = true; foreach (ExperimentNode node in experiment.Vertices) { IDecision decisionMetadata = node.Data.Metadata as IDecision; if (decisionMetadata != null) { try { //build successor nodes label id lookup Dictionary <string, string> successorNodeLabelIdLookup = PrepareSuccessorNodesLabelIdLookup(node, experiment); Dictionary <string, string> predeccessorsOutputsNameTypeLookup = PreparePredeccessorsOutputsNameTypeLookup(node, availableInputMappingsPerNode); node.ClearError(); BuildSourceAndCompileDecisionModule(decisionMetadata, successorNodeLabelIdLookup, predeccessorsOutputsNameTypeLookup, workspaceTypesDirectories, loggerNameRoot); } catch (ArgumentException ex) { noErrors = false; node.SetError(ex.Message); } } } return(noErrors); }
private TestLog PrepareLogging(GameObject go, IExperiment experiment, string id) { //parents itself under Logging thing - under master go.transform.SetParent(MasterLog.Instance.transform); Log = new Log(id, "test_" + experiment.Name); return(this); }
private static void CreateReport(IExperiment exp) { Console.WriteLine("Creating report for metaexperiment: " + exp.Name); try { //Set the current directory. Directory.SetCurrentDirectory(Path.Combine(exp.OutputDirectory, "results")); } catch (DirectoryNotFoundException e) { Console.WriteLine("The specified results directory " + Path.Combine(ApplicationConfig.EXECDIR, "results") + " does not exist. {0}", e); } ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = ApplicationConfig.ROOTDIR + "bin/report.sh"; startInfo.Arguments = "" + exp.Name; try { // Start the process with the info we specified. // Call WaitForExit and then the using statement will close. using (Process report = Process.Start(startInfo)) { report.WaitForExit(); } } catch { // Log error. } }
private static bool SerializeExperimentToStream(IExperiment experiment, string filename) { bool success = false; try { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NamespaceHandling = NamespaceHandling.OmitDuplicates; settings.OmitXmlDeclaration = true; settings.ConformanceLevel = ConformanceLevel.Fragment; settings.CloseOutput = false; //create the xml writer MemoryStream fileStream = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(fileStream, settings)) { ExperimentSerializer.SerializeExperiment(writer, experiment); writer.Flush(); writer.Close(); //we enrcypt the file before save it Crypto.EncryptFile(fileStream, filename); } success = true; } catch (System.Security.SecurityException ex) { System.Diagnostics.Debug.Write("Security exception while serializing experiment to Xml " + ex); } return(success); }
public Iterative_Greens_Function(IExperiment exp, double[,] potential) : base(exp.Temperature) { this.exp = exp; // this.dx = exp.Dx_Dens; this.dy = exp.Dy_Dens; // this.nx = exp.Nx_Dens; this.ny = exp.Ny_Dens; dx = 100; dy = 100; nx = 50; ny = 20; alphax_prime = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dx * dx); alphay_prime = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dy * dy); potential_xy = potential; DensityoS = new DoubleMatrix(nx, ny); // nx = 100; ny = 1; // alphax = -1.0;// -0.5 * Physics_Base.hbar * Physics_Base.hbar / (Physics_Base.mass * dx * dx); // alphay = 0.0;// -0.5 * Physics_Base.hbar * Physics_Base.hbar / (Physics_Base.mass * dy * dy); alphax = alphax_prime / alphax_prime; alphay = alphay_prime / alphax_prime; }
private IExperiment GetExperimentClass() { var choice = Console.ReadLine(); Console.WriteLine(); IExperiment experiment = default(IExperiment); int choiceInt = default(int); bool isChoiceInt = Int32.TryParse(choice, out choiceInt); if (isChoiceInt) { bool exists = this.ExperimentBook.TryGetValue(choiceInt, out experiment); if (exists) { return(experiment); } else { return(null); } } else { return(null); } }
/// <summary> /// Validates the entire experiment. /// It validates the structure of the experimental graph, /// validates all inputs and outputs, /// checks if all components are in the component library. /// </summary> /// <param name="experiment">The experiment.</param> /// <param name="vertices">The vertices, that has been parsed from the start node. Nodes that are not connected to the start are being skipped.</param> /// <param name="edges">The edges, that has been parsed from the start node.</param> /// <returns> /// true if there is no errors, false, if errors has been detected /// </returns> public static bool ValidateExperiment(IExperiment experiment, out List<ExperimentNode> vertices, out List<ExperimentNodeConnection> edges, List<string> workspaceTypesDirectories, bool validateInputMapping, LoggerNameRoot loggerNameRoot) { bool noErrors = GraphValidator.Validate(experiment, out vertices, out edges); if (noErrors) { var availableInputMappingsPerNode = new TraceLab.Core.Utilities.InputMappings(experiment); if (validateInputMapping) { noErrors = InputMappingValidator.Validate(experiment, availableInputMappingsPerNode); } if (noErrors) { //recompile all decisions noErrors = TraceLab.Core.Decisions.DecisionCompilationRunner.CompileAllDecisionNodes(experiment, availableInputMappingsPerNode, workspaceTypesDirectories, loggerNameRoot); } } if (noErrors) { noErrors = ValidComponents(vertices); } return noErrors; }
/////////////////////////////////////////////////////////////////////// // Constructor (Pull the experiment out of the app and store it for // use) /////////////////////////////////////////////////////////////////////// public AsynAcquireSample(ILightFieldApplication app) { InitializeComponent(); application_ = app; experiment_ = application_.Experiment; fileManager_ = application_.FileManager; }
/////////////////////////////////////////////////////////////////////// public void Activate(ILightFieldApplication app) { // Capture Interface LightFieldApplication = app; experiment_ = app.Experiment; menuEnabled_ = CheckSystem(); processEnabled_ = false; // Create transformation object if we have a camera (via menu enabled) if (menuEnabled_) { CreateTransformationObject(); } // Listen to region of interest result changed and re-compute the buffers to match the // region List <string> settings = new List <string>(); settings.Add(CameraSettings.ReadoutControlRegionsOfInterestResult); experiment_.FilterSettingChanged(settings); experiment_.SettingChanged += experiment__SettingChanged; // Connect to experiment device changed (when camera is added this add-in is active, and // if a camera is removed then this add-in is disabled. experiment_.ExperimentUpdated += experiment__ExperimentUpdated; // Connect to the data received event experiment_.ImageDataSetReceived += experimentDataReady; }
// /////// // // Methods // // /////// // // Invoked when another experiment is selected in the editor or when the // editor reloads // Obtains the concrete experiment and determines the names of the // generation and navigation parameter sets, also updating the number of // scenarios private void OnChangeExperiment() { // Obtain and instantiate the concrete experiment according to the // selected experiment name _experiment = _experiments[_experimentName] .GetConstructor(Type.EmptyTypes) .Invoke(null) as IExperiment; // Update names of generation parameter sets _genParamSets = _experiment.GenParamSet.Keys.ToArray(); Array.Sort(_genParamSets); if (!_genParamSets.Contains(_genParamSet)) { _genParamSet = _genParamSets[0]; } // Update names of navigation parameter sets _navParamSets = _experiment.NavParamSet.Keys.ToArray(); Array.Sort(_navParamSets); if (!_navParamSets.Contains(_navParamSet)) { _navParamSet = _navParamSets[0]; } // Update number of scenarios OnChangeNumberOfScenarios(); }
public static void RemoveEmptyStateFirstLine(IExperiment experiment, ExperimentParameters parameters) { if (parameters.TutorialManager.MainWindow.TryBeginInvoke(RemoveEmptyStateFirstLine, experiment, parameters)) { return; } var emptyStateButton = parameters.TutorialManager .MainWindow .GetView <TimerEntryListView>() .Entries .FindName("emptyListText") as Button; if (emptyStateButton != null) { var stackPanel = emptyStateButton.Content as StackPanel; if (stackPanel != null) { if (stackPanel.Children.Count == 3) { stackPanel.Children[0].RemoveFromParent(); } return; } } throw new Exception(string.Format("Unable to modify empty state in experiment {0}.", experiment.Id)); }
void cmdStartTransfer_Click(object sender, RoutedEventArgs e) { (measurementInterface as FET_IV).expTransfer_FET_Chart.Children.RemoveAll(typeof(LineGraph)); (measurementInterface as FET_IV).expTransfer_FET_Chart.Legend.Visibility = System.Windows.Visibility.Visible; expStartInfo = (measurementInterface as FET_IV).DataContext; var settings = expStartInfo as FET_IVModel; if (driver != null) { driver.Dispose(); } if (measureDevice != null) { measureDevice.Dispose(); } driver = new VisaDevice(settings.KeithleyRscName); measureDevice = new Keithley26xxB <Keithley2602B>(driver); var DrainSourceSMU = measureDevice[settings.TransferVdsChannel]; var GateSMU = measureDevice[settings.TransferVgChannel]; experiment = new FET_Transfer_Experiment(DrainSourceSMU, GateSMU) as IExperiment; experiment.ExpStarted += onExperimentStarted; experiment.DataArrived += expTransfer_FET_dataArrived; experiment.Progress += experimentProgress; experiment.Status += experimentStatus; experiment.Start(expStartInfo); }
/// <summary> /// Validates the entire experiment. /// It validates the structure of the experimental graph, /// validates all inputs and outputs, /// checks if all components are in the component library. /// </summary> /// <param name="experiment">The experiment.</param> /// <returns>true if there is no errors, false, if errors has been detected</returns> public static bool ValidateExperiment(IExperiment experiment, List <string> workspaceTypesDirectories, LoggerNameRoot loggerNameRoot) { List <ExperimentNode> vertices; List <ExperimentNodeConnection> edges; return(ValidateExperiment(experiment, out vertices, out edges, workspaceTypesDirectories, true, loggerNameRoot)); }
/// <summary> /// Compiles all decision nodes code and loops code in the given experiment /// </summary> /// <param name="experiment">The experiment.</param> /// <param name="availableInputMappingsPerNode">The available input mappings per node.</param> /// <param name="workspaceTypesDirectories">The workspace types directories.</param> /// <param name="loggerNameRoot">The logger name root.</param> /// <returns> /// true if there were no errors, otherwise false /// </returns> public static bool CompileAllDecisionNodes(IExperiment experiment, InputMappings availableInputMappingsPerNode, List<string> workspaceTypesDirectories, LoggerNameRoot loggerNameRoot) { bool noErrors = true; foreach (ExperimentNode node in experiment.Vertices) { IDecision decisionMetadata = node.Data.Metadata as IDecision; if (decisionMetadata != null) { try { //build successor nodes label id lookup Dictionary<string, string> successorNodeLabelIdLookup = PrepareSuccessorNodesLabelIdLookup(node, experiment); Dictionary<string, string> predeccessorsOutputsNameTypeLookup = PreparePredeccessorsOutputsNameTypeLookup(node, availableInputMappingsPerNode); node.ClearError(); BuildSourceAndCompileDecisionModule(decisionMetadata, successorNodeLabelIdLookup, predeccessorsOutputsNameTypeLookup, workspaceTypesDirectories, loggerNameRoot); } catch (ArgumentException ex) { noErrors = false; node.SetError(ex.Message); } } } return noErrors; }
public override enExperimentStatus Configure(IExperiment parent, string resultsFilePath) { FBC = new FeedbackController(log); FBC.Settings = Settings.FeedbackController; FBC.FBPositionUpdated += FBC_FBPositionUpdated; if (!FBC.Initialize().HasFlag(enuFeedbackStatusFlags.Ready)) { return(enExperimentStatus.Error); } this.parent = parent; ResultsFilePath = resultsFilePath; string cords = ""; ExperimentContainer container = parent as ExperimentContainer; this.parent = parent; if (container != null) { cords = container.ChildIndexer(); if (cords != "") { cords = " " + cords; } } ResultsFileName = "AutoapproachExperiment - " + Name + cords + ".dat"; TransducerChannel signalChan = FBC.Settings.TransducerChannels[FBC.Settings.Channel]; string headerString = "Experiment: AutoapproachExperiment - " + Name + "\r\n"; string unit = (signalChan.Prefix == enuPrefix.none) ? signalChan.Unit : signalChan.Prefix + signalChan.Unit; string[] dataColumnHeaders = new string[] { "Z-Position [µm]", signalChan.Name + " [" + unit + "]" }; headerString += "Positioner: " + FBC.Settings.Positioner + "\r\n"; headerString += "Sensor: " + FBC.Settings.Channel + "\r\n"; writeHeader(headerString, dataColumnHeaders.ToArray(), settingsObj: Settings, positionColumns: false, timeColumn: true); // Init ResultData experimentData = new Generic2DExperimentData(); experimentData.axisNames.Add(new string[] { "Z-Position", signalChan.Name }); experimentData.axisUnits.Add(new string[] { "µm", unit }); experimentData.data.Add(new double[2][]); signalData = new List <double>(128); positionData = new List <double>(128); experimentData.datasetNames.Add("Autoapproach"); experimentData_PA = new Generic2DExperimentData(); experimentData_PA.axisNames.Add(new string[] { "Time", signalChan.Name }); experimentData_PA.axisUnits.Add(new string[] { "s", unit }); experimentData_PA.data.Add(new double[2][]); signalData_PA = new List <double>(128); timeData_PA = new List <double>(128); experimentData_PA.datasetNames.Add("Post approach"); status = enExperimentStatus.Idle; return(status); }
internal static IExperimentRunner CreateExperimentRunner(IExperiment currentExperiment, TraceLab.Core.Workspaces.Workspace workspace, TraceLab.Core.Components.ComponentsLibrary library) { // Allow all nodes to send info to logs - if any targets exist. foreach (TraceLab.Core.Experiments.ExperimentNode node in currentExperiment.Vertices) { var componentNode = node as TraceLab.Core.Experiments.ComponentNode; if (componentNode != null) { foreach (TraceLab.Core.Settings.LogLevelItem item in componentNode.Data.Metadata.LogLevels) { item.IsEnabled = true; } } } RunnableNodeFactory templateGraphNodesFactory = new RunnableNodeFactory(workspace); TraceLab.Core.ExperimentExecution.RunnableExperimentBase template = GraphAdapter.Adapt(currentExperiment, templateGraphNodesFactory, library, workspace.TypeDirectories); var dispatcher = ExperimentRunnerFactory.CreateExperimentRunner(template); return(dispatcher); }
internal static void BFSTraverseExperiment(IExperiment experiment, ExperimentNode startFromNode, TraverseTask Task) { //traverse graph down from the node Queue <ExperimentNode> traversingQueue = new Queue <ExperimentNode>(); HashSet <ExperimentNode> foundVertices = new HashSet <ExperimentNode>(); traversingQueue.Enqueue(startFromNode); while (traversingQueue.Count > 0) { ExperimentNode currentNode = traversingQueue.Dequeue(); //do some stuff Task(currentNode); foreach (ExperimentNodeConnection edge in experiment.OutEdges(currentNode)) { if (foundVertices.Contains(edge.Target) == false) { traversingQueue.Enqueue(edge.Target); foundVertices.Add(edge.Target); } } } }
private void addExperiment(IExperiment experiment) { bool isOk = (experiment.getParameters() is IParameterList); if (isOk) { this.jwriter.writeStartObject(); this.jwriter.writePropertyName("experiment_id"); this.jwriter.writeValue(experiment.getId()); if (!String.IsNullOrEmpty(experiment.getName())) { this.jwriter.writePropertyName("name"); this.jwriter.writeValue(experiment.getName()); } if (!String.IsNullOrEmpty(experiment.getDescription())) { this.jwriter.writePropertyName("description"); this.jwriter.writeValue(experiment.getDescription()); } this.jwriter.writePropertyName("parametercollection"); this.addParameterCollection((IParameterList)experiment.getParameters()); this.jwriter.writeEndObject(); } else { throw new ArgumentException("Property 'experiment.getParameters()' of argument " + "'experiment' must be of type IParameterList."); } }
/// <summary> /// Compiles the decision. /// </summary> /// <param name="node">The node.</param> /// <param name="experiment">The experiment.</param> /// <param name="workspaceTypesDirectories">The workspace types directories.</param> /// <param name="loggerNameRoot">The logger name root.</param> private static void CompileDecisionInternal(ExperimentNode node, IExperiment experiment, List <string> workspaceTypesDirectories, LoggerNameRoot loggerNameRoot, Dictionary <string, string> successorNodeLabelIdLookup) { InputMappings availableInputMappingsPerNode = new InputMappings(experiment); Dictionary <string, string> predeccessorsOutputsNameTypeLookup = PreparePredeccessorsOutputsNameTypeLookup(node, availableInputMappingsPerNode); IDecision decisionMetadata = (IDecision)node.Data.Metadata; try { if (decisionMetadata != null) { node.ClearError(); BuildSourceAndCompileDecisionModule(decisionMetadata, successorNodeLabelIdLookup, predeccessorsOutputsNameTypeLookup, workspaceTypesDirectories, loggerNameRoot); decisionMetadata.CompilationStatus = TraceLab.Core.Components.CompilationStatus.Successful; } } catch (ArgumentException ex) { decisionMetadata.CompilationStatus = TraceLab.Core.Components.CompilationStatus.Failed; node.SetError(ex.Message); } }
/// <summary> /// Serializes the experiment to XML file. /// </summary> /// <param name="experiment">The experiment to be saved.</param> /// <param name="filename">The filename.</param> /// <returns>true if saving was successful, otherwise false</returns> private static bool SerializeExperimentToXml(IExperiment experiment, string filename) { bool success = false; try { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NamespaceHandling = NamespaceHandling.OmitDuplicates; settings.OmitXmlDeclaration = true; //create the xml writer using (XmlWriter writer = XmlWriter.Create(filename, settings)) { ExperimentSerializer.SerializeExperiment(writer, experiment); } success = true; } catch (System.Security.SecurityException ex) { System.Diagnostics.Debug.Write("Security exception while serializing experiment to Xml " + ex); } return(success); }
public ThreeD_EffectiveBandSolver(IExperiment exp) : base(exp) { tx = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dx * dx); ty = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dy * dy); tz = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dz * dz); }
/// <summary> /// Saves the experiment to specified filename. /// </summary> /// <param name="experiment">The experiment to be saved.</param> /// <param name="fileName">The filename.</param> /// <param name="watchFile">if set to <c>true</c> it adds FileSystemWatcher to monitore directory in which the file is located. It is optional, because there are situations, /// where experiment is being saved and loaded from temporary file folder.</param> /// <returns>true if saving was successful, otherwise false</returns> public static bool Save(IExperiment experiment, string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } string oldExperimentFilePath = experiment.ExperimentInfo.FilePath; bool success = false; try { //update its FilePath info to the new file location experiment.ExperimentInfo.FilePath = fileName; success = Save(experiment); } finally { if (success == false) { experiment.ExperimentInfo.FilePath = oldExperimentFilePath; //go back to old filepath } } return(success); }
/// <summary> /// Generates the scope node at the given position. /// </summary> /// <param name="scopeName">Name of the scope.</param> /// <param name="experiment">The experiment to which new component is added.</param> /// <param name="positionX">The position X.</param> /// <param name="positionY">The position Y.</param> /// <returns></returns> private static ScopeNode GenerateScopeNode(string scopeName, IExperiment experiment, double positionX, double positionY, double width, double height) { var data = new SerializedVertexDataWithSize(); data.X = positionX; data.Y = positionY; data.Width = width; data.Height = height; string componentId = Guid.NewGuid().ToString(); var componentGraph = new CompositeComponentEditableGraph(true); if (componentGraph.References != null) { componentGraph.References = experiment.References.CopyCollection(); } data.Metadata = new ScopeMetadata(componentGraph, scopeName, System.IO.Path.GetDirectoryName(experiment.ExperimentInfo.FilePath)); string componentNodeId = Guid.NewGuid().ToString(); string componentName = data.Metadata.Label; var scopeNode = new ScopeNode(Guid.NewGuid().ToString(), data); return(scopeNode); }
public void PathUpdatedOnSaveExperiment() { IExperiment experiment = ExperimentManager.New(); Assert.IsNotNull(experiment); Assert.AreEqual(2, experiment.VertexCount); Assert.IsTrue(string.IsNullOrEmpty(experiment.ExperimentInfo.FilePath)); string filename = System.IO.Path.Combine(AppContext.BaseTestDirectory, "testSave.gml"); try { bool success = ExperimentManager.Save(experiment, filename); Assert.IsTrue(success); Assert.IsTrue(File.Exists(filename)); //did experiment info filepath got update on save Assert.AreEqual(experiment.ExperimentInfo.FilePath, filename); } finally { if (File.Exists(filename)) { //cleanup File.Delete(filename); } } }
public override enExperimentStatus Configure(IExperiment parent, string resultsFilePath) { this.parent = parent; ResultsFilePath = resultsFilePath; ResultsFileName = "SetSingleValue - " + Name + ".dat"; activeChannels = new List <TransducerChannel>(); foreach (string chan in Settings.Channels) { if ((chan != null) && (chan != "NONE") && (transducerChannels.ContainsKey(chan))) { //ITransducer transducer = HWStore[Settings.Channel.Split('.').First()] as ITransducer; TransducerChannel channel = transducerChannels[chan]; activeChannels.Add(channel); } } if (activeChannels.Count == 0) { log.Add("No transducer channel selected or invalid configuration", "Error"); return(enExperimentStatus.Error); } status = enExperimentStatus.Idle; return(status); }
public ThreeD_Density_Base(IExperiment exp) : base(exp.Temperature) { this.exp = exp; this.dx = exp.Dx_Dens; this.dy = exp.Dy_Dens; this.dz = exp.Dz_Dens; this.xmin = exp.Xmin_Dens; this.ymin = exp.Ymin_Dens; this.zmin = exp.Zmin_Dens; this.nx = exp.Nx_Dens; this.ny = exp.Ny_Dens; this.nz = exp.Nz_Dens; }
public OneD_Density_Base(IExperiment exp) : base(exp.Temperature) { this.exp = exp; this.dz = exp.Dz_Dens; this.zmin = exp.Zmin_Dens; this.nz = exp.Nz_Dens; }
private static void RemoveReference(IExperiment experiment, Core.PackageSystem.PackageReference packageReference) { if (experiment.References.Contains(packageReference)) { experiment.References.Remove(packageReference); RemoveReferenceFromScopes(experiment, packageReference); } }
public static void AddReference(IExperiment experiment, PackageReference packageReference) { if (!experiment.References.Contains(packageReference)) { experiment.References.Add(packageReference); AddReferenceToScopes(experiment, packageReference); } }
public static void RemoveReference(IExperiment experiment, PackageReference packageReference) { if (experiment.References.Contains(packageReference)) { experiment.References.Remove(packageReference); RemoveReferenceFromScopes(experiment, packageReference); } }
public TwoplusOneD_ThomasFermiSolver(IExperiment exp) : base(exp) { tx = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dx * dx); ty = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dy * dy); tz = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dz * dz); g_2d = mass / (Math.PI * Physics_Base.hbar); }
public TwoD_Density_Base(IExperiment exp, Carrier carrier_type) : this(exp) { this.carrier_type = carrier_type; if (carrier_type == Carrier.hole) { Change_Charge(+1.0 * Physics_Base.q_e); Change_Mass(0.51 * Physics_Base.m_e); } }
public BaseLevelExperimentViewModel(IExperiment experiment, BaseLevelExperimentViewModel owner) { if (experiment == null) throw new ArgumentNullException("experiment", "Wrapped experiment cannot be null"); m_experiment = experiment; m_experiment.PropertyChanged += m_experiment_PropertyChanged; Owner = owner; ToggleInfoPaneForNode = new DelegateCommand(ToggleInfoPaneForNodeFunc); }
public OneD_DFTSolver(IExperiment exp, Carrier carrier_type) : this(exp) { this.carrier_type = carrier_type; if (carrier_type == Carrier.hole) { Change_Charge(+1.0 * Physics_Base.q_e); Change_Mass(0.51 * Physics_Base.m_e); t = -0.5 * Physics_Base.hbar * Physics_Base.hbar / (mass * dz * dz); } }
public override void WriteGraphAttributes(System.Xml.XmlWriter writer, IExperiment flow) { base.WriteGraphAttributes(writer, flow); //and also serialize the baseline results if (m_baseline != null) { var serializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(TLExperimentResults), null); serializer.Serialize(writer, m_baseline); } }
public void DrawExperiment(IExperiment experiment, bool editable) { foreach(ExperimentNode node in experiment.Vertices) { DrawComponent(node, editable); } foreach(ExperimentNodeConnection edge in experiment.Edges) { DrawEdge(edge, editable); } }
/// <summary> /// Adapts the specified experiment into runnable experiment. /// Adapt method validates given experiment and builds runnable experiment which is going to be executed by the experiment runner. /// During adapation the experiment is validated. /// In case of detected error in the experiment, this method returns empty RunnableExperimentBase with no nodes and no edges. /// There are several errors that can be detected. /// There are nodes connected to start, but not to graph end. /// Loops without decisions nodes. /// Input mappings are incorrect. /// Failed component load or instantiation, especially in case of incorrect configuration values. /// </summary> /// <param name="experiment">The experiment which is going to be adapted into RunnableExperiment..</param> /// <param name="nodesFactory">The nodes factory, by which all nodes in runnable experiment are created..</param> /// <param name="library">The library of components.</param> /// <param name="workspaceTypeDirectories">The workspace type directories.</param> /// <returns> /// Runnable experiment that experiment is going to execute, pruned from nodes that are not connected to main flow beginning at Start node. /// In case of detected error in the experiment, this method returns empty RunnableExperimentBase with no nodes and no edges. /// </returns> public static RunnableExperimentBase Adapt(IExperiment experiment, IRunnableNodeFactory nodesFactory, Components.ComponentsLibrary library, List<string> workspaceTypeDirectories) { LoggerNameRoot loggerNameRoot = new LoggerNameRoot(experiment.ExperimentInfo.Id); // Create the new domain for the runnable experiment with whatever current security evidence we're running with. // The components app domain is the app domain which components assemblies are going to be loaded into. var helper = new TraceLab.Core.Components.LibraryHelper(workspaceTypeDirectories); AppDomain componentsAppDomain = helper.CreateDomain(experiment.ExperimentInfo.Id); return Adapt(experiment, loggerNameRoot, nodesFactory, library, workspaceTypeDirectories, componentsAppDomain, new System.Threading.ManualResetEvent(false), true); }
/// <summary> /// Serializes the experiment. /// </summary> /// <param name="experiment">The experiment to be serialized.</param> /// <param name="writer">The writer.</param> /// <param name="library">The library - needed for post XML processing to determine if components has been located in library, and needed to show their definition and description.</param> public static void SerializeExperiment(XmlWriter writer, IExperiment experiment) { var factory = new ExperimentFactoryWriter(); experiment.SerializeToXml(writer, (QuickGraph.VertexIdentity<ExperimentNode>)(v => v.ID), (QuickGraph.EdgeIdentity<ExperimentNode, ExperimentNodeConnection>)(e => e.ID), "graph", "node", "edge", "", factory.WriteGraphAttributes, factory.WriteNodeAttributes, factory.WriteEdgeAttributes); }
private void CollectNodesInExperiment(IExperiment experiment, ref List<ExperimentNode> nodes) { foreach (ExperimentNode currentNode in experiment.Vertices) { ScopeNodeBase scopeNode = currentNode as ScopeNodeBase; if (scopeNode != null) { CollectNodesInExperiment(scopeNode.CompositeComponentMetadata.ComponentGraph, ref nodes); } nodes.Add(currentNode); } }
/// <summary> /// Serializes the experiment. /// </summary> /// <param name="experiment">The experiment to be serialized.</param> /// <param name="writer">The writer.</param> /// <param name="library">The library.</param> /// <param name="workspaceTypeDirectories">The workspace type directories.</param> /// <param name="dataRoot">The data root.</param> public void SerializeExperiment(IExperiment experiment, TLExperimentResults baseline, XmlWriter writer) { //use standard factory to serialize the experiment var factory = new BenchmarkExperimentFactory(baseline); experiment.SerializeToXml(writer, (QuickGraph.VertexIdentity<ExperimentNode>)(v => v.ID), (QuickGraph.EdgeIdentity<ExperimentNode, ExperimentNodeConnection>)(e => e.ID), "graph", "node", "edge", "", factory.WriteGraphAttributes, factory.WriteNodeAttributes, factory.WriteEdgeAttributes); }
private static void DFSVisit(ExperimentNode node, bool pathFromDecision, IExperiment graph, Dictionary<ExperimentNode, GraphNodeStatus> verticesStatuses, ref List<ExperimentNode> vertices, ref List<ExperimentNodeConnection> edges, ref bool noErrors) { verticesStatuses.Add(node, GraphNodeStatus.Visiting); GraphNodeStatus status = GraphNodeStatus.HasNoPathToEnd; bool isDecision = (node.Data.Metadata is DecisionMetadata); bool comingFromDecision = isDecision || pathFromDecision; if (graph.OutEdges(node).Count<ExperimentNodeConnection>() > 0) { foreach (ExperimentNodeConnection edge in graph.OutEdges(node)) { if (verticesStatuses.ContainsKey(edge.Target) == false) { DFSVisit(edge.Target, comingFromDecision, graph, verticesStatuses, ref vertices, ref edges, ref noErrors); } if (verticesStatuses[edge.Target].Equals(GraphNodeStatus.Visiting) == true && comingFromDecision == false) { noErrors = false; SetErrorOnNode(node, "Circular link detected."); } else if (verticesStatuses[edge.Target].Equals(GraphNodeStatus.HasPathToEnd) == true || (verticesStatuses[edge.Target].Equals(GraphNodeStatus.Visiting) == true && comingFromDecision == true)) { // Add EDGE and its SOURCE and TARGET vertices only if Path was completed to END. // or if it is circular link that is coming from the decision status = GraphNodeStatus.HasPathToEnd; if (vertices.Contains(edge.Target) == false) vertices.Add(edge.Target); if (vertices.Contains(edge.Source) == false) //current node, ie. node == edge.Source vertices.Add(edge.Source); edges.Add(edge); } } } else { if (node.Data.Metadata is EndNodeMetadata) { status = GraphNodeStatus.HasPathToEnd; } else { noErrors = false; SetErrorOnNode(node, "Unable to detect path to the END node."); } } verticesStatuses[node] = status; }
/// <summary> /// This validator validates the graph structure of the experiment. It analizes all paths weather they are connected properly to the end. /// Traverse experiment from start. Any nodes that are not connected are skipped. /// If back edge is detected then it is marked as error at the edge source node. /// Any paths that are not completed till the END node are skipped - it could be run then without those branches, but currently they are marked with error. /// </summary> /// <param name="m_experiment">Graph m_experiment, that allow retrieves out edges for each node</param> /// <param name="vertices">returns list of vertices that are going to be included in the experiment run. It skips vertices that are not connected to main flow beginning at the START node</param> /// <param name="edges">returns list of edges that are going to be included in the experiment run. It skips edges that are on the path that does no go to END node.</param> /// <returns>returns true if there are no errors; false if any error has been detected</returns> public static bool Validate(IExperiment experiment, out List<ExperimentNode> vertices, out List<ExperimentNodeConnection> edges) { bool noErrors = true; vertices = new List<ExperimentNode>(); edges = new List<ExperimentNodeConnection>(); Dictionary<ExperimentNode, GraphNodeStatus> verticesStatuses = new Dictionary<ExperimentNode, GraphNodeStatus>(); DFSVisit(experiment.StartNode, false, experiment, verticesStatuses, ref vertices, ref edges, ref noErrors); return noErrors; }
/// <summary> /// Adapts the specified experiment into runnable experiment. /// Adapt method validates given experiment and builds runnable experiment which is going to be executed by the experiment runner. /// During adapation the experiment is validated. /// In case of detected error in the experiment, this method returns empty RunnableExperimentBase with no nodes and no edges. /// There are several errors that can be detected. /// There are nodes connected to start, but not to graph end. /// Loops without decisions nodes. /// Input mappings are incorrect. /// Failed component load or instantiation, especially in case of incorrect configuration values. /// </summary> /// <param name="experiment">The experiment which is going to be adapted into RunnableExperiment..</param> /// <param name="loggerNameRoot">The logger name root - needed so that the logs are specific per experiment and experiment window.</param> /// <param name="nodesFactory">The nodes factory, by which all nodes in runnable experiment are created..</param> /// <param name="library">The library of components.</param> /// <param name="workspaceTypeDirectories">The workspace type directories.</param> /// <param name="componentsAppDomain">The components app domain is the app domain which components assemblies are going to be loaded into.</param> /// <param name="terminateExperimentExecutionResetEvent">The event that allows signalling termination of the experiment</param> /// <returns> /// Runnable experiment that experiment is going to execute, pruned from nodes that are not connected to main flow beginning at Start node. /// In case of detected error in the experiment, this method returns empty RunnableExperimentBase with no nodes and no edges. /// </returns> public static RunnableExperimentBase Adapt(IExperiment experiment, LoggerNameRoot loggerNameRoot, IRunnableNodeFactory nodesFactory, Components.ComponentsLibrary library, List<string> workspaceTypeDirectories, AppDomain componentsAppDomain, System.Threading.ManualResetEvent terminateExperimentExecutionResetEvent, bool validateInputMapping) { RunnableExperimentBase runnableExperiment = new RunnableExperiment(nodesFactory, library, componentsAppDomain, terminateExperimentExecutionResetEvent); List<ExperimentNode> vertices; List<ExperimentNodeConnection> edges; bool noErrors = ExperimentValidator.ValidateExperiment(experiment, out vertices, out edges, workspaceTypeDirectories, validateInputMapping, loggerNameRoot); if (noErrors) { foreach (ExperimentNode node in vertices) { try { runnableExperiment.AddNode(node.ID, node.Data.Metadata, loggerNameRoot); } catch (TraceLab.Core.Exceptions.IncorrectSubTemplateException ex) { runnableExperiment.Clear(); noErrors = false; NLog.LogManager.GetCurrentClassLogger().Error(ex.Message); node.SetError(ex.Message); break; } catch (Exception ex) { runnableExperiment.Clear(); noErrors = false; string msg = "Unable to initialize component: " + ex.Message; NLog.LogManager.GetCurrentClassLogger().Error(msg, ex); node.SetError(msg); break; } } } if (noErrors) { foreach (ExperimentNodeConnection edge in edges) { runnableExperiment.AddDirectedEdge(edge.Source.ID, edge.Target.ID); } } return runnableExperiment; }
private static void RemoveReferenceFromScopes(IExperiment experiment, Core.PackageSystem.PackageReference packageReference) { foreach (ExperimentNode node in experiment.Vertices) { ScopeNodeBase scopeNode = node as ScopeNodeBase; if (scopeNode != null) { var subgraph = scopeNode.CompositeComponentMetadata.ComponentGraph; if (subgraph.References.Contains(packageReference)) { subgraph.References.Remove(packageReference); } } } }
/// <summary> /// Validates if the list of outputs from incoming vertices satisfies all the inputs for all vertices in the lookup. /// </summary> /// <returns>true, if all vertices have correct mapping, false if there is any node with input that is not satisfied by previous outputs.</returns> public static bool Validate(IExperiment experiment, InputMappings availableInputMappingsPerNode) { bool retVal = true; foreach (ExperimentNode currentNode in availableInputMappingsPerNode.Nodes) { bool validationResults = ValidateInputMapping(currentNode, availableInputMappingsPerNode[currentNode]); if (retVal != false) { retVal = validationResults; } } return retVal; }
private static void AddReferenceToScopes(IExperiment experiment, PackageReference packageReference) { foreach (ExperimentNode node in experiment.Vertices) { ScopeNodeBase scopeNode = node as ScopeNodeBase; if (scopeNode != null) { var subgraph = scopeNode.CompositeComponentMetadata.ComponentGraph; if (!subgraph.References.Contains(packageReference)) { subgraph.References.Add(packageReference); } } } }
public PackageManagerViewModel(IExperiment experiment) { m_experiment = experiment; var references = new HashSet<string>(experiment.References.Select((a) => { return a.ID; })); var manager = TraceLab.Core.PackageSystem.PackageManager.Instance; foreach (TraceLabSDK.PackageSystem.IPackage package in manager) { var packageVM = new PackageViewModel(package); packageVM.IsCheckedChanged += packageVM_IsCheckedChanged; if (references.Contains(package.ID)) { packageVM.IsChecked = true; } m_packages.Add(packageVM); } }
/// <summary> /// Tries the find experiment. /// </summary> /// <param name="dependencyObject">The dependency object from which the parent is going to be searched for</param> /// <param name="experiment">The experiment.</param> /// <returns></returns> protected static bool TryFindExperiment(DependencyObject dependencyObject, out IExperiment experiment) { bool found = false; experiment = null; if (dependencyObject != null) { var nodeInfoContainer = dependencyObject.GetParent<TraceLab.UI.WPF.Views.Nodes.NodeInfoContainer>(null); var componentNodeInfo = nodeInfoContainer.DataContext as ExperimentNodeInfo; if (componentNodeInfo != null) { experiment = componentNodeInfo.Node.Owner; found = true; } } return found; }
/// <summary> /// Compiles the code of the single decision node or loop scope node. It handles DecisionNode and LoopScopeNode slightly differently. /// Method. /// </summary> /// <param name="node">The node.</param> /// <param name="experiment">The experiment.</param> /// <param name="workspaceTypesDirectories">The workspace types directories.</param> /// <param name="loggerNameRoot">The logger name root.</param> public static void CompileDecision(ExperimentNode node, IExperiment experiment, List<string> workspaceTypesDirectories, LoggerNameRoot loggerNameRoot) { ExperimentDecisionNode decisionNode = node as ExperimentDecisionNode; if (decisionNode != null) { Dictionary<string, string> successorNodeLabelIdLookup = PrepareSuccessorNodesLabelIdLookup(node, experiment); CompileDecisionInternal(decisionNode, experiment, workspaceTypesDirectories, loggerNameRoot, successorNodeLabelIdLookup); } else { LoopScopeNode loopScopeNode = node as LoopScopeNode; if (loopScopeNode != null) { //loop scope does not need successor nodes lookups, so pass in empty dictionary Dictionary<string, string> successorNodeLabelIdLookup = new Dictionary<string, string>(); CompileDecisionInternal(loopScopeNode, experiment, workspaceTypesDirectories, loggerNameRoot, successorNodeLabelIdLookup); } } }
/// <summary> /// Tries the find experiment from the given combobox item. /// </summary> /// <param name="comboBoxItem">The combo box item.</param> /// <param name="experiment">The experiment.</param> /// <returns>true if experiment has been found</returns> private static bool TryFindExperiment(ComboBoxItem comboBoxItem, out IExperiment experiment) { bool found = false; experiment = null; if (comboBoxItem != null) { //find combobox var combobox = comboBoxItem.GetParent<ItemsPresenter>(null); if (combobox != null) { if (TryFindExperiment(combobox.TemplatedParent, out experiment)) { found = true; } } } return found; }