public SVM_Matlab(string path, double sigma, double gamma, Kernel kernel, ImageVector[] goodImages, ImageVector[] badImages) { type = "SVM"; this.goodImages = goodImages; this.badImages = badImages; learnedTrue = new bool[goodImages.Length]; learnedFalse = new bool[badImages.Length]; confidenceTrue = new double[goodImages.Length]; confidenceFalse = new double[badImages.Length]; restartTest(); userPath = path + "\\SVM_" + getKernel(kernel) + "_" + sigma; resultPath = userPath + "\\" + sigma + "_" + gamma; learn = GetLearnCommand(userPath, sigma, gamma, kernel); learn_Test = GetLearnCommand_Test(userPath, sigma, gamma, kernel,goodImages[0].getNumOfParameters()); decide = GetDecideCommand(userPath, kernel); decide_Test = GetDecideCommand_Test(userPath, kernel, goodImages[0].getNumOfParameters()); matlab = new MLApp.MLApp(); cd = "cd " + smartAlbum.getMatlabDirectory(); matlab.Execute(cd); }
/// <summary> /// This method executes the specific matlab code of the vectorfield. The stream- or pathlines are handed to matlab. /// </summary> /// <param name="matlab">The instance of the matlab connection</param> public void executeMatlab(MLApp.MLApp matlab) { matlab.Execute("highNumberSamples = 0;"); if (freshySimulated) { bool first = true; foreach (Line line in rungeLines) { if (line.Points.Count > 0) { string t = Util.getLineMatrix(line); if (first) { matlab.Execute("connections = [" + Util.getLineMatrix(line)); first = false; } else { matlab.Execute("connections = [connections; " + Util.getLineMatrix(line)); } } } freshySimulated = false; } }
/// <summary> /// Constructor of the Mainwindow. The matlab connection and other variables get initialized. /// </summary> public MainWindow() { InitializeComponent(); clusterCanvas = new Canvas[5]; clusterCanvas[0] = clusterCanvas1; clusterCanvas[1] = clusterCanvas2; clusterCanvas[2] = clusterCanvas3; clusterCanvas[3] = clusterCanvas4; clusterCanvas[4] = clusterCanvas5; matlab = new MLApp.MLApp(); string current = Directory.GetCurrentDirectory(); using (StreamReader reader = new StreamReader("SVP.config")) { matlabPath = current + "\\" + reader.ReadLine(); ressourcePath = current + "\\" + reader.ReadLine(); } //current = "cd '" + current.Substring(0, current.IndexOf("SVP")) + "Matlab'"; current = "cd '" + matlabPath + "'"; matlab.Execute(current); travel = new Travel(); toPolylineConverter = new Util(); }
private void Record_BT_Click(object sender, EventArgs e) { MLApp.MLApp matlab = null; Type matlabAppType = System.Type.GetTypeFromProgID("Matlab.Application"); matlab = System.Activator.CreateInstance(matlabAppType) as MLApp.MLApp; string command; if (Record_BT.Text == "录音") { command = "R = audiorecorder( 16000, 8 ,1) ; record(R);"; matlab.Visible = 0; matlab.Execute(command); Record_BT.Text = "停止"; } else if (Record_BT.Text == "停止") { string outpath = Application.StartupPath + "/speak.wav"; command = "stop(R); myspeech = getaudiodata(R);audiowrite('" + outpath + "', myspeech, 16000);"; matlab.Visible = 0; matlab.Execute(command); Record_BT.Text = "录音"; } }
private void button2_Click(object sender, EventArgs e)//修正值摁钮 { string str = System.Environment.CurrentDirectory; MLApp.MLApp matlab = new MLApp.MLApp(); string comm = ""; matlab.Execute(@"cd " + str + "\\第二步计算"); //matlab.Execute(""); // Define the output object result = null; // Call the MATLAB function myfunc matlab.Feval("T", 1, out result); // matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world"); // Display result object[] res = result as object[]; ans = (double[, ])res[0]; for (int i = 0; i < 48; i++) { textBox3.Text += "第" + (i + 1).ToString() + "组解: " + " dx: " + ans[i, 0].ToString() + " dy: " + ans[i, 1].ToString() + " dz: " + ans[i, 2].ToString() + Environment.NewLine; } //textBox3.Text = ans[1,1].ToString(); // ans = result; // MessageBox.Show(result); // Console.WriteLine(res[0]); // Console.WriteLine(res[1]); // Console.ReadLine(); // n = excel.solve1();//解第二个方程 //for(int i=0;i<48;i++) //{ textBox3.Text += "第" + (i + 1).ToString() + "组解: " + " dx: " + n[i * 3].ToString() + " dy: " + n[i * 3 + 1].ToString() + " dz: " + n[i * 3 + 2].ToString()+Environment.NewLine; } }
protected void EnhanceImage_Click(object sender, EventArgs e) { MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute("cd " + Server.MapPath(MATLAB_FUNCTIONS_FOLDER)); object result = null; App_Code.Image image = App_Code.SqlUtilities.GetImage(int.Parse(Request["id"])); string[] temp = image.Path.Split('/'); string imageName = temp[temp.Length - 1]; matlab.Feval("enhance", 1, out result, Server.MapPath(image.Path), imageName, loggedUsername); object[] res = result as object[]; string resultPath = "~/Images/" + loggedUsername + "/" + (string)res[0]; System.Web.UI.WebControls.Image imageControl = (System.Web.UI.WebControls.Image)ThumbnailsHolder.Controls[1]; imageControl.ImageUrl = resultPath; if (ViewState["editedImagePath"] != null) { DeleteImage(null, null); } ViewState["editedImagePath"] = resultPath; AddSaveDeleteButtons(); }
public void Init(double rsm_lb, double rsm_ub, int pc_b) { step = 0.01; States = new List <RTPState>(); Observations = new List <RTPObservation>(); ModelSamples = new List <Sample>(); SystemSamples = new List <Sample>(); EstimateSamples = new List <Sample>(); //TestEstimateSamples = new List<Sample>(); MBuilder = Matrix <double> .Build; VBuilder = Vector <double> .Build; E = new Matrix <double> [N]; F = new Matrix <double> [M]; for (int i = 0; i < N; i++) { E[i] = MBuilder.Dense(N, 1); E[i][i, 0] = 1; } for (int i = 0; i < M; i++) { F[i] = MBuilder.Dense(M, 1); F[i][i, 0] = 1; } Matlab = new MLApp.MLApp(); DefineStates(rsm_lb, rsm_ub); DefineObservations(pc_b); //ModelParamsInit(); }
private RecognitionProvider() { _matlab = new MLApp.MLApp(); // Change to the directory where the function is located _matlab.Execute(@"cd " + AppDomain.CurrentDomain.BaseDirectory + "ReconScript/"); }
public NetGAxaml() { InitializeComponent(); matlab = new MLApp.MLApp(); matlab.Visible = 0; }
public BestHybrid() { InitializeComponent(); matlab = new MLApp.MLApp(); matlab.Visible = 0; }
public KNN_SVM(string path, double sigma, double gamma, Kernel kernel, int k, ImageVector[] goodImages, ImageVector[] badImages) { type = "KNN & SVM"; svm = new SVM_Matlab(path, sigma, gamma, (SVM_Matlab.Kernel)kernel, goodImages, badImages); knn = new KNN_Matlab(path, k, goodImages, badImages); totalImages = 0; this.goodImages = goodImages; this.badImages = badImages; learnedTrue = new bool[goodImages.Length]; learnedFalse = new bool[badImages.Length]; restartTest(); userPath = path + "\\KNN_SVM"; resultPath = userPath + "\\sigma_" + sigma + "_gamma_" + gamma; learn = GetLearnCommand(userPath, sigma, gamma, kernel); decideSVM = GetDecideCommandSVM(userPath, kernel); decideKNN = GetDecideCommandKNN(userPath, k); matlab = new MLApp.MLApp(); cd = "cd " + smartAlbum.getMatlabDirectory(); matlab.Execute(cd); }
// Start Matlab. /// <summary> /// Starts with Program, either connects to COM-Enabled Matlab or starts a Matlab File. /// </summary> /// <remarks> The call "enableservice('AutomationServer',true);" COM-enables Matlab and ensures it doesn't close with the program.</remarks> public static void MatlabStartup() { // Matlab Startup and Connection to Desktop Type MatlabType = Type.GetTypeFromProgID("Matlab.Desktop.Application"); try { //To make sure COM enabled for running Matlab //Connect to an open Matlab // Execute = enableservice('AutomationServer',true); matlab = (MLApp.MLApp)Marshal.GetActiveObject("Matlab.Desktop.Application"); } catch (System.Runtime.InteropServices.COMException ex1) { try { //Open Matlab program matlab = (MLApp.MLApp)Activator.CreateInstance(MatlabType); //IMPORTANT: Stops exiting from Matlab when program closes matlab.Execute("enableservice('AutomationServer',true);"); } catch (System.Runtime.InteropServices.COMException ex2) { // Matlab not on computer. } } }
private void masstochargeMatlab_Range(double startXval, double endXval) { int selectedfileNumber_start = Convert.ToInt32(startXval) + 1; int selectedfileNumber_end = Convert.ToInt32(endXval) + 1; int selectedFileNumber = selectedfileNumber_end - selectedfileNumber_start + 1; if (selectedfileNumber_start > intFileNumber || selectedfileNumber_start > intFileNumber) { //not to over max Xvalue selectedfileNumber_start = intFileNumber; selectedfileNumber_end = intFileNumber; } // Create the MATLAB instance MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute(matlab_path); object resultdata = null; //There is no xLength Data if (xLength == 0) { xLength = 25000; } matlab.Feval("mTcPlot_Range", 2, out resultdata, selectedfileNumber_start, selectedfileNumber_end, xLength); object[] res = resultdata as object[]; object_To_double(res); }
public HybridArimaSVM() { InitializeComponent(); matlab = new MLApp.MLApp(); matlab.Visible = 0; }
private void getMatlabdata() { // Create the MATLAB instance MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute(matlab_path); object resultdata = null; matlab.Feval("binfileReader2", 2, out resultdata); object[] res = resultdata as object[]; double[,] intensity = (double[, ])res[0]; fileNumber = (double)res[1]; intFileNumber = Convert.ToInt32(fileNumber); dintensity = new double[intensity.Length]; for (int i = 0; i < intensity.Length; i++) { dintensity[i] = intensity[0, i]; } InitialZedGraph(); }
public MainModelView(Canvas canvas, Window master) { if (Properties.Settings.Default.ModelPath.Length == 0) { Properties.Settings.Default.ModelPath = Directory.GetCurrentDirectory(); } if (Properties.Settings.Default.AppPath.Length == 0) { Properties.Settings.Default.AppPath = Directory.GetCurrentDirectory(); } this._master = master; this.TrashCommand = new Command(this.TrashAction, this.TrashActionCan); this.BackCommand = new Command(this.BackAction, this.BackActionCan); this.ProcessCommand = new Command(this.ProcessAction, this.ProcessActionCan); this.TrueCommand = new Command(this.TrueAction, this.TrueActionCan); this.FalseCommand = new Command(this.FalseAction, this.FalseActionCan); this.OpenMatriceCommand = new Command(this.OpenMatriceAction); this.ResetDataCommand = new Command(this.ResetDataAction); this.OpenSettingsCommand = new Command(this.OpenSettingsAction); this.matrix = new Stack <Point>(); this.canvas = canvas; this.FunctionPredictor = Properties.Settings.Default.NameModel; this.Data = Data.Open(this.FunctionPredictor); this.state = false; this.StateValid = true; this.worker = new BackgroundWorker() { WorkerSupportsCancellation = true }; this.worker.RunWorkerCompleted += worker_RunWorkerCompleted; this.worker.DoWork += (sender, e) => { try { bool[,] image = new bool[28, 28]; foreach (Point point in this.matrix) { image[(int)point.Y * 2, (int)point.X * 2] = true; image[(int)point.Y * 2 + 1, (int)point.X * 2] = true; image[(int)point.Y * 2, (int)point.X * 2 + 1] = true; image[(int)point.Y * 2 + 1, (int)point.X * 2 + 1] = true; } MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute("cd " + Properties.Settings.Default.ModelPath); matlab.PutWorkspaceData("X", "base", image); matlab.Execute(@"label = " + this.FunctionPredictor + "(X)"); var label = matlab.GetVariable("label", "base"); e.Result = label; } catch (Exception err) { e.Result = err.Message; } }; this.InProcess = "Hidden"; }
private void reducereEBtn_Click(object sender, EventArgs e) { if (pathTB.Text.Trim() != "") { try { MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute(@"cd E:\FisiereWAV"); object result = null; matlab.Feval("MyFunc3", 1, out result, selectedFile, "REcho-", selectedFilePath); rezultatFiltrareTB.Text = "REcho-" + selectedFile; soundFilter = new SoundPlayer(@"E:\FisiereWAV\Workspace\" + "REcho-" + selectedFile); soundFilter.Play(); pictureBox1.Visible = true; pictureBox1.ImageLocation = @"E:\FisiereWAV\Workspace\" + "REcho-" + Path.GetFileNameWithoutExtension(selectedFile) + ".jpg"; } catch (Exception ex) { MessageBox.Show("Eroare la conexiunea cu MATLAB: " + ex.Message); } } else { MessageBox.Show("Nu ati ales fisierul audio!", reducereEBtn.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void MatlabAction(string sWPID, string sPathOfApp) { // Folgenden Zeilen basieren auf einem Beispiel von Matlab // Create the MATLAB instance String sFileName = System.IO.Path.GetFileName(sPathOfApp); String sFilePath = sPathOfApp.Replace("\\" + sFileName, ""); Type MatlabType = Type.GetTypeFromProgID("Matlab.Desktop.Application"); MLApp.MLApp matlab = (MLApp.MLApp)Activator.CreateInstance(MatlabType); // Change to the directory where the function is located String sExecutePath = "cd " + sFilePath; matlab.Execute(sExecutePath); // Define the output object result = null; // Call the MATLAB function myfunc matlab.Feval(sFileName.Replace(".m", ""), 1, out result, sWPID); // Display result object[] res = result as object[]; // Hier könnte noch eine Abfrage folgen ob das Result ein Fehler ist !!! Ist noch nicht definiert wie das aussieht. }
// Constructor CalibrationClient(HoloDataClient holoDataClient, NatNetClient natNetClient) { logStartTime_ = System.DateTime.Now; outputFile_ = outputFile_ + logStartTime_.ToString("_yyMMdd_hhmmss") + ".csv"; WriteToLog("# hl_pos_x,hl_pos_y,hl_pos_z,hl_rot_w,hl_rot_x,hl_rot_y,hl_rot_z,rb_pos_x,rb_pos_y,rb_pos_z,rb_rot_w,rb_rot_x,rb_rot_y,rb_rot_z,timestamp"); outputFile1_ = outputFile1_ + logStartTime_.ToString("_yyMMdd_hhmmss") + ".csv"; outputFile2_ = outputFile2_ + logStartTime_.ToString("_yyMMdd_hhmmss") + ".csv"; // Create the MATLAB instance matlab_ = new MLApp.MLApp(); // Change to the directory where the function is located string startupPath = Environment.CurrentDirectory; string pathCmd = string.Format("cd {0}\\..\\..", startupPath); matlab_.Execute(pathCmd); holoDataClient_ = holoDataClient; natNetClient_ = natNetClient; holoDataClient_.StartFetchLoop(2000); holoDataClient_.OnPoseUpdate = PoseDataReceived; nnStartFetchLoop(20); }
public static void reCreateMatlabCom() { matlab = null; matlab = new MLApp.MLApp { Visible = 0 }; }
private void weights_ga_matlab() { string path_MatlabFunctions = Environment.CurrentDirectory; // داده ورودی باید حتما در مسیر توابع متلب باشد // توابع هزینه هم باید با عنوان //cost_func //در همان مسیر توابع متلب تعریف شوند. MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute("clear vars all;"); matlab.Execute(@"cd '" + path_MatlabFunctions + "'"); string temp = matlab.Execute("a=2"); string x = matlab.Execute(@"[x]=GeneticForWighting()"); // string IDX = matlab.Execute("IDX"); try { matlab.Execute("quit"); } catch (Exception ex) { } }
public ArimaGA() { InitializeComponent(); matlab = new MLApp.MLApp(); matlab.Visible = 0; }
public int maxGAIteretionInHybrid = 20; //30 public HybridComplexModel() { InitializeComponent(); matlab = new MLApp.MLApp(); matlab.Visible = 0; }
public OdeSolver() { new Thread(() => { _matlab = new MLApp.MLApp(); _matlab.Execute($"cd {Directory.GetCurrentDirectory()}\\Matlab"); }).Start(); }
public void pcaVisualization(double[] Orignal, double[] Pca) { MLApp.MLApp matlb = new MLApp.MLApp(); matlb.Execute("cd C:\\temp"); object res = null; matlb.Feval("pcaVisualizeFunc", 1, out res, Orignal, Pca); }
public static void PlotarVetor(double[] vetor) { MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Visible = 0; //matlab.PutWorkspaceData("a", "base", matriz); matlab.PutWorkspaceData("a", "base", vetor); matlab.Execute("plot(a);"); }
private void runMATLAB(string s, string[] args) { MLApp.MLApp matlab = new MLApp.MLApp(); object matlabResult = null; matlab.Execute(@"cd C:\work\temp\images\simple"); matlab.Feval(s, 0, out matlabResult, args[0], args[1], args[2]); }
private void InitBackgroundMatlabService() { _matlab = new MLApp.MLApp(); if (_matlab == null) { throw new ApplicationException("Matlab com object is null"); } }
// 初始化 matlab 引擎 private MLApp.MLApp initMatlabEp() { MLApp.MLApp matlab = null; Type matlabAppType = System.Type.GetTypeFromProgID("Matlab.Application"); matlab = System.Activator.CreateInstance(matlabAppType) as MLApp.MLApp; return(matlab); }
public List <RecommendedArtist> GetRecommendationsOnGenre(User fan, List <Artist> artists, int noOfRecommendations) { List <Artist> recommendedArtists = new List <Artist>(); List <RecommendedArtist> recommendations = new List <RecommendedArtist>(); if (fan.Genres.Count == 0) { return(recommendations); } String genresTxt = ""; using (var unitOfWork = new UnitOfWork()) { var genresRepository = unitOfWork.GetRepository <Genre>(); foreach (Genre g in genresRepository.GetAll()) { if (fan.Genres.Where(x => x.Id == g.Id).Count() != 0) { genresTxt += fan.Id + "," + g.Id + "," + 1 + ";"; } else { genresTxt += fan.Id + "," + g.Id + "," + 0 + ";"; } } } MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute(@"cd C:\Users\Luiza"); object result = null; // Call the MATLAB function myfunc matlab.Feval("genreSimilarity", 1, out result, genresTxt); // Display result object[] res = result as object[]; object arr = res[0]; double[,] pairs = (double[, ])arr; for (int i = 0; i < pairs.Length / 2; i++) { var artist = artists.Where(a => a.User.Role == (int)RolesEnum.ARTIST && a.ArtistId == pairs[i, 0]).FirstOrDefault(); if (artist != null && pairs[i, 1] * 100 > 10 && artist.Ratings.Where(r => r.FanId == fan.Id).Count() == 0) { recommendations.Add(new RecommendedArtist { Id = artist.ArtistId, Name = artist.User.Name, Score = pairs[i, 1] * 100, PictureUrl = artist.PictureUrl, Why = "Acest artist iti este recomandat deoarece genurile tale muzicale preferate se potrivesc cu ale sale" + " in proportie de " + Math.Round(pairs[i, 1] * 100, 2) + "%." }); } } return(recommendations.Take(noOfRecommendations).ToList()); }
public void signalVisualization(double[] Orignal, double[] Pca, double[] Ica) { MLApp.MLApp matlb = new MLApp.MLApp(); matlb.Execute("cd C:\\temp"); object res = null; matlb.Feval("myfunc2", 1, out res, Orignal, Pca, Ica); }
public SimTF() { MWinstance = new MLApp.MLApp(); result = ""; resultD = 0; resultobj = new object(); Mlocation = "D:/SimTF"; result = MWinstance.Execute("cd('" + Mlocation + "');"); }
private void txtMalSpeech_Click(object sender, EventArgs e) { if (txtFilePath.Text != "") { MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Visible = 0; matlab.Execute("VoiceChange('" + txtFilePath.Text + "',0)"); } else MessageBox.Show("Select a file", "No file selected", MessageBoxButtons.OK, MessageBoxIcon.Error); }
public SVM_Matlab(string path, double sigma, double gamma, Kernel kernel, ImageVector[] allImages) { type = "SVM"; this.allImages = allImages; filesTrueResults = new Algorithm[allImages.Length]; for (int i = 0; i < filesTrueResults.Length; i++) filesTrueResults[i] = LearningAlgorithmML.Algorithm.BAD; userPath = path + "\\SVM_" + getKernel(kernel) + "_" + sigma; resultPath = userPath + "\\" + sigma + "_" + gamma; learn = GetLearnCommand(userPath, sigma, gamma, kernel); decide = GetDecideCommand(userPath, kernel); matlab = new MLApp.MLApp(); cd = "cd " + smartAlbum.getMatlabDirectory(); matlab.Execute(cd); }
private void proc() { MLApp.MLApp Call_Matlab = new MLApp.MLApp(); Call_Matlab.Visible = 0; object result = null; Call_Matlab.Execute(@"cd C:\MatlabProcessing"); try { Call_Matlab.Feval("MAIN_PROCESSING", 1, out result, PthTs, PthTr, PthAl); Res = result as object[]; MessageBox.Show(Res[0].ToString()); Call_Matlab.Quit(); Marshal.ReleaseComObject(Call_Matlab); } catch (Exception e) { Marshal.ReleaseComObject(Call_Matlab); MessageBox.Show(e.ToString()); } }
//private double runConf; public KNN_Matlab(string path, int k, ImageVector[] goodImages, ImageVector[] badImages) { type = "KNN"; this.goodImages = goodImages; this.badImages = badImages; learnedTrue = new bool[goodImages.Length]; learnedFalse = new bool[badImages.Length]; restartTest(); userPath = path + "\\KNN"; resultPath = userPath + "\\" + k; decide = GetCommand(userPath, k); decide_Test = GetCommand_Test(userPath, k, goodImages[0].getNumOfParameters()); matlab = new MLApp.MLApp(); cd = "cd " + smartAlbum.getMatlabDirectory(); matlab.Execute(cd); }
public MATLABWrapper(string _mcodepath, string _groupID) { groupID = _groupID; mcodepath = new DirectoryInfo(_mcodepath); if (!mcodepath.Exists) { throw new Exception("The mcode folder can not be found."); } var activationContext = Type.GetTypeFromProgID("matlab.application.single"); matlab = (MLApp.MLApp)Activator.CreateInstance(activationContext); matlab.Visible = 0; String output; output= matlab.Execute("cd " + mcodepath.FullName); output=matlab.Execute("pwd"); var currentDirCheck = matlab.GetVariable("ans", "base"); DirectoryInfo currentDirCheckDi = new DirectoryInfo(currentDirCheck); if (currentDirCheckDi.FullName != mcodepath.FullName) { throw new Exception("Changing MATLAB working directory to mcode directory failed. Working directory stuck at " + currentDirCheck); } }
public Tuple<double[], double> Execute(double l1, double l2, double l3) { MLApp.MLApp matlab = new MLApp.MLApp(); var appFolder = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ); var workFolder = Path.Combine(appFolder, "Matlab"); matlab.Execute(@"cd " + workFolder); object result = null; matlab.Feval("Calculation", 2, out result, l1, l2, l3); // Display result object[] res = (object[])result; var x = (double[,])res[0]; var fval = (double)res[1]; return Tuple.Create(new double[] { x[0, 0], x[0, 1], x[0, 2] }, fval); }
public bool Decide() { // Get list of files in folders String[] files = Testing.GetFilesFromDirectory(decidePath).ToArray(); string csvPath = userPath + "\\Decide.txt"; string resultPath = userPath + "\\Result.txt"; for (int i = 0; i < files.Length; i++) { System.IO.StreamWriter file = new System.IO.StreamWriter(@csvPath, false); ImageVector vec = new ImageVector(files[i], null); file.WriteLine(vec.getAllParameters(false)); file.Close(); MLApp.MLApp matlab = new MLApp.MLApp(); string cd = "cd C:\\Users\\anoach\\Desktop\\papa_matlab"; //string exe = "albumSvm('" + userPath + "');"; string exe = "albumKnn('" + userPath + "', " + 1 + ");"; //K = 1 matlab.Execute(cd); matlab.Execute(exe); string[] readText = File.ReadAllLines(resultPath); if (readText[0] == "1") { Console.WriteLine("Good Image"); } else { Console.WriteLine("Bad Image. Delete it"); File.Delete(files[i]); } } return true; }
static void Main(string[] args) { /////////////////////////////////////// Looking for a file /////////////////////////////////////// int m = 0, n; //Learning the value of m(Number of training examples) and n(number of atributes) using (TextReader reader = File.OpenText("C:/Users/laerte/Desktop/ex1data1.txt")) { string linha = reader.ReadLine(); string[] temp = linha.Split(','); n = temp.Length - 1; while (linha != null) { m++; linha = reader.ReadLine(); } reader.Close(); } double[,] X = new double[m, n + 1]; double[,] y = new double[m, 1]; double[,] theta = new double[n + 1, 1]; //filling out the matrix X, the vector y, and the vector theta using (TextReader reader = File.OpenText("C:/Users/laerte/Desktop/ex1data1.txt")) { int i = 0; string linha = reader.ReadLine(); while (linha != null) { string[] temp = linha.Split(','); X[i, 0] = 1; for (int j = 1; j < n + 1; j++) { //Console.Write(temp[j - 1]); X[i, j] = Convert.ToDouble(temp[j - 1]); } y[i, 0] = Convert.ToDouble(temp[n]); linha = reader.ReadLine(); i++; } reader.Close(); } for (int i = 0; i < n + 1; i++) { theta[i, 0] = 0; } /* ////////////////////////////////////////////// PRINT //////////////////////////////////////////////// for (int i = 0; i < m; i++) { for (int j = 0; j < n + 1; j++) { Console.Write("X[{0}][{1}] = {2} ", i, j, X[i, j]); } Console.Write("\n"); } for (int i = 0; i < m; i++) { Console.Write("y[{0}] = {1}\n", i, y[i,0]); } for (int i = 0; i < n + 1; i++) { Console.Write("theta[{0}] = {1}\n", i, theta[i,0]); } */ ////////////////////////////////////////////Matlab calculations///////////////////////////////////////////// // Create the MATLAB instance MLApp.MLApp matlab = new MLApp.MLApp(); // Change to the directory where the function is located matlab.Execute(@"cd C:\Users\laerte\Desktop"); // Define the output object result = null; // Call the MATLAB function myfunc matlab.Execute("clear all"); matlab.Feval("computeCost", 1, out result, X, y, theta); // Display result object[] res = result as object[]; Console.WriteLine("Computing the cost J = " + res[0]); // Closing the matblab window //matlab.Quit(); // Wait until fisnih Console.ReadLine(); }
private void init() { matlab = new MLApp.MLApp(); matlab.Visible = 0; runsCount = errorCount = 0; data = new List<MyNumber>(); ResourceDictionary rd = new ResourceDictionary(); rd.Source = new Uri("MyResourceDictionary.xaml", UriKind.Relative); this.Resources.MergedDictionaries.Add(rd); worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); }
void matlab(string code) { string[] lines, var_temp; List<string> variables=new List<string>(); List<string> var_result = new List<string>(); int var_count=0; lines = code.Split('\r'); MLApp.MLApp matlab = new MLApp.MLApp(); for (int a = 0; a < lines.Count(); a++) { if(lines[a].StartsWith("\n")) lines[a]=lines[a].Remove(0,1); string i = matlab.Execute(lines[a]); //TODO osetrit ak nie je spravny matlabovsky prikaz if (lines[a].Contains('=')) //ak obsahuje = prekpokladame ze pred = je premenna ktoru posleme spet { var_temp = lines[a].Split('=')[0].Split(", ".ToCharArray()); for (int b = 0; b < var_temp.Count(); b++) { if (var_temp[b].StartsWith("[")) //odstranime [] ak nahodou obsahuje { var_temp[b]=var_temp[b].Remove(0, 1); } if (var_temp[b].EndsWith("]")) //odstranime [] ak nahodou obsahuje { var_temp[b]=var_temp[b].Remove(var_temp[b].Length - 1, 1); } if (!variables.Contains(var_temp[b]) && var_temp[b]!="") { variables.Add(var_temp[b]); var_count++; } } } //matlab.Execute(lines[a]); } foreach (string variable in variables) { try { var_result.Add(Convert.ToString(matlab.GetVariable(variable, "base"))); } catch(Exception e) { var_result.Add(variable + ": ??? Undefined function or variable"); } } for (int a = 0; a < variables.Count; a++) { result += variables[a] + " = " + var_result[a] + "\r\n"; } }
static void Main(string[] args) { /////////////////////////////////////// Looking for a file /////////////////////////////////////// // Variables used in matlab //double lambda = 1.5; //Reading the file to get the size of lines and columns of R and Y, which will be used in training colloborative filtering int num_jobs_init; int num_users_init; int num_features; using (TextReader readerR = File.OpenText("C:/Users/larissaf/Desktop/files/Y.txt")) { num_jobs_init = 0; string line = readerR.ReadLine(); string[] temp = line.Split('\t'); num_users_init = temp.Length; while (line != null) { line = readerR.ReadLine(); num_jobs_init++; } readerR.Close(); } //it needs to be between 1 and num_users_init (PUT A VERIFICATION HERE) /* Console.Write("Write down the user number that will receive job recommendation from 1 to {0}\n", num_users_init); string read = Console.ReadLine(); * */ int user_number = 1; StreamWriter writetext = new StreamWriter("results.txt"); string space = "\t"; string new_line = "\n"; while (user_number <= 100) { //Now we read R and Y from theirs files (-1 because I will remove the chosen user from the matrixes) double[,] Y = new double[num_jobs_init, num_users_init - 1]; double[,] R = new double[num_jobs_init, num_users_init - 1]; // Movie rating file for a user double[,] my_ratings = new double[num_jobs_init, 1]; //reading Y_training using (TextReader readerY = File.OpenText("C:/Users/larissaf/Desktop/files/Y.txt")) { int i = 0; string line = readerY.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); int k = 0; for (int j = 0; j < num_users_init; j++) { if (j != (user_number - 1)) { Y[i, k] = Convert.ToDouble(temp[j]); k++; } else my_ratings[i, 0] = Convert.ToDouble(temp[j]); } line = readerY.ReadLine(); i++; } readerY.Close(); } //reading R_training using (TextReader readerR = File.OpenText("C:/Users/larissaf/Desktop/files/R.txt")) { int i = 0; string line = readerR.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); int k = 0; for (int j = 0; j < num_users_init; j++) { if (j != (user_number - 1)) { R[i, k] = Convert.ToDouble(temp[j]); k++; } } line = readerR.ReadLine(); i++; } readerR.Close(); } //reading X to get the number of features using (TextReader readerX = File.OpenText("C:/Users/larissaf/Desktop/files/X.txt")) { num_features = 0; string line = readerX.ReadLine(); if (line != null) { string[] temp = line.Split('\t'); num_features = temp.Length; } readerX.Close(); } //allocating the X matriz double[,] X = new double[num_jobs_init, num_features]; //reading X_training using (TextReader readerX = File.OpenText("C:/Users/larissaf/Desktop/files/X.txt")) { int i = 0; string line = readerX.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); for (int j = 0; j < num_features; j++) { X[i, j] = Convert.ToDouble(temp[j]); } line = readerX.ReadLine(); i++; } readerX.Close(); } // make sure that the data will be zero for all the positions using (TextReader reader_movies_ratings = File.OpenText("C:/Users/larissaf/Desktop/files/one_user_rating.txt")) { int i = 0; string line = reader_movies_ratings.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); my_ratings[Convert.ToInt32(temp[0]) - 1, 0] = Convert.ToInt32(temp[1]); line = reader_movies_ratings.ReadLine(); i++; } reader_movies_ratings.Close(); } // Job names string[] job_list = new string[num_jobs_init]; using (TextReader reader_movie_list = File.OpenText("C:/Users/larissaf/Desktop/files/job_names.txt")) { string line = reader_movie_list.ReadLine(); int i = 0; while (line != null) { job_list[i] = line; line = reader_movie_list.ReadLine(); i++; } reader_movie_list.Close(); } ////////////////////////////////////////////Matlab calculations/////////////////////////////////////////// // Create the MATLAB instance MLApp.MLApp matlab = new MLApp.MLApp(); // Change to the directory where the functions are located --- always use the desktop to make tests to avoid problems with pathway matlab.Execute(@"cd C:\Users\larissaf\Desktop\files"); // Define the output to print the final result object result_movies_search = null; matlab.Execute("my_ratings"); // Movie erecommendations script matlab.Feval("scriptGeneration", 6, out result_movies_search, my_ratings, job_list, Y, R, X, num_features); object[] res = result_movies_search as object[]; //Console.Write("{0} {1}", res[5], job_list[(int)(((double[,])res[0])[0, 0]) - 1]); // ---------------------------------------------------------------------- // writetext.Write(res[5]); int len = ((double[,])res[0]).Length; for (int i = 0; i < len; i++) { writetext.Write(job_list[(int)(((double[,])res[0])[i, 0]) - 1]); writetext.Write(space); writetext.Write((((double[,])res[1])[i, 0])); writetext.Write(space); writetext.Write(job_list[(int)(((double[,])res[2])[i, 0]) - 1]); writetext.Write(space); writetext.Write((((double[,])res[3])[i, 0])); writetext.Write(space); writetext.Write((((double[,])res[4])[i, 0])); writetext.Write(space); writetext.Write(user_number); writetext.Write(new_line); } user_number++; } // while ends writetext.Close(); Console.Write(" DONE"); // Wait until fisnih Console.ReadLine(); }
private void button_run_matlab_Click(object sender, EventArgs e) { // Create the MATLAB instance MLApp.MLApp matlab = new MLApp.MLApp(); // Change to the directory where the function is located matlab.Execute(@"cd('c:/Users/Boris/Documents/Visual Studio 2010/Projects/FieldFox_1/Matlab')"); string cmd = @"folderToObject('C:\\FieldFox\\" + folderName + @"')"; matlab.Execute(cmd); }
static void Main(string[] args) { int num_jobs_init; int num_users_init; int num_features; int user_number = 1; //Reading the file to get the size of lines and columns of R and Y, //which will be used in training colloborative filtering. using (TextReader readerR = File.OpenText("C:/Users/larissaf/Desktop/files/Y.txt")) { num_jobs_init = 0; string line = readerR.ReadLine(); string[] temp = line.Split('\t'); num_users_init = temp.Length; while (line != null) { line = readerR.ReadLine(); num_jobs_init++; } readerR.Close(); } //File that is going to be written with the Top ten jobs and ratings and similarity for all users StreamWriter writetext = new StreamWriter("results.txt"); //Dictionary that contains a list of top ten jobs compared with other jobs for each user Dictionary<int, List<MyData>> finalList = new Dictionary<int, List<MyData>>(); //consider that we have 100 users (we can ask how may and change the while-condition) while (user_number <= 100) { //Now we read R and Y from theirs files (-1 because I will remove the chosen user from the matrixes) double[,] Y = new double[num_jobs_init, num_users_init - 1]; double[,] R = new double[num_jobs_init, num_users_init - 1]; // Movie rating file for a user double[,] my_ratings = new double[num_jobs_init, 1]; //reading Y_training using (TextReader readerY = File.OpenText("C:/Users/larissaf/Desktop/files/Y.txt")) { int i = 0; string line = readerY.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); int k = 0; for (int j = 0; j < num_users_init; j++) { if (j != (user_number - 1)) { Y[i, k] = Convert.ToDouble(temp[j]); k++; } else my_ratings[i, 0] = Convert.ToDouble(temp[j]); } line = readerY.ReadLine(); i++; } readerY.Close(); } //reading R_training using (TextReader readerR = File.OpenText("C:/Users/larissaf/Desktop/files/R.txt")) { int i = 0; string line = readerR.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); int k = 0; for (int j = 0; j < num_users_init; j++) { if (j != (user_number - 1)) { R[i, k] = Convert.ToDouble(temp[j]); k++; } } line = readerR.ReadLine(); i++; } readerR.Close(); } //reading X to get the number of features using (TextReader readerX = File.OpenText("C:/Users/larissaf/Desktop/files/X.txt")) { num_features = 0; string line = readerX.ReadLine(); if (line != null) { string[] temp = line.Split('\t'); num_features = temp.Length; } readerX.Close(); } //allocating the X matriz double[,] X = new double[num_jobs_init, num_features]; //reading X_training using (TextReader readerX = File.OpenText("C:/Users/larissaf/Desktop/files/X.txt")) { int i = 0; string line = readerX.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); for (int j = 0; j < num_features; j++) { X[i, j] = Convert.ToDouble(temp[j]); } line = readerX.ReadLine(); i++; } readerX.Close(); } /* using (TextReader reader_movies_ratings = File.OpenText("C:/Users/larissaf/Desktop/files/one_user_rating.txt")) { int i = 0; string line = reader_movies_ratings.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); my_ratings[Convert.ToInt32(temp[0]) - 1, 0] = Convert.ToInt32(temp[1]); line = reader_movies_ratings.ReadLine(); i++; } reader_movies_ratings.Close(); }*/ // Job names string[] job_list = new string[num_jobs_init]; using (TextReader reader_movie_list = File.OpenText("C:/Users/larissaf/Desktop/files/job_names.txt")) { string line = reader_movie_list.ReadLine(); int i = 0; while (line != null) { job_list[i] = line; line = reader_movie_list.ReadLine(); i++; } reader_movie_list.Close(); } ////////////////////////////////////////////Matlab calculations/////////////////////////////////////////// // Create the MATLAB instance MLApp.MLApp matlab = new MLApp.MLApp(); //this is used to do not show the matlab window //matlab.Visible = 0; // Change to the directory where the functions are located --- always use the desktop to make tests to avoid problems with pathway matlab.Execute(@"cd C:\Users\larissaf\Desktop\files"); // Define the output to print the final result object result_movies_search = null; matlab.Execute("my_ratings"); // Movie erecommendations script matlab.Feval("scriptGeneration", 6, out result_movies_search, my_ratings, job_list, Y, R, X, num_features); object[] res = result_movies_search as object[]; int len = ((double[,])res[0]).Length; //for each one of the users, we will have a list containg all the comparassions between the top ten jobs for him, and //the other jobs (that had similarity >= 70%) List<MyData> mylist = new List<MyData>(); MyData aux; for (int i = 0; i < len; i++) { //adding a new element in the list for each user. aux = new MyData(job_list[(int)(((double[,])res[0])[i, 0]) - 1], (((double[,])res[1])[i, 0]), job_list[(int)(((double[,])res[2])[i, 0]) - 1], (((double[,])res[3])[i, 0]), (((double[,])res[4])[i, 0])); mylist.Add(aux); writetext.Write(job_list[(int)(((double[,])res[0])[i, 0]) - 1] + "\t"); writetext.Write((((double[,])res[1])[i, 0]) + "\t"); writetext.Write(job_list[(int)(((double[,])res[2])[i, 0]) - 1] + "\t"); writetext.Write((((double[,])res[3])[i, 0]) + "\t"); writetext.Write((((double[,])res[4])[i, 0]) + "\t"); writetext.Write(user_number + "\n"); } //adding the list at the Dictionary for each user finalList.Add(user_number, mylist); user_number++; } // while ends writetext.Close(); //creating a instance of an object for user 1: (maybe send null) dataResult avgs = new dataResult(null, 10); avgs.WriteInAFile(finalList); Console.WriteLine("DONE"); // Wait until fisnih Console.ReadLine(); }
protected void plot(LinkedList<double> ds) { MLApp.MLApp matlab = new MLApp.MLApp(); System.Array pr = new double[ds.Count+1]; System.Array pi = new double[ds.Count+1]; int i = 0; foreach (double d in ds) { pr.SetValue(d, i); i++; pi.SetValue(i, i); } matlab.PutFullMatrix("plottable", "base", pi, pr); matlab.Execute("plot(plottable)"); }
private void Interanl_Learn(ImageVector[] goodImages, ImageVector[] badImages, int[] subsetFilesTrue, int[] subsetFilesFalse) { string csvPathLearn = userPath + "\\Learn.txt"; System.IO.StreamWriter fileLearn = new System.IO.StreamWriter(@csvPathLearn, false); for (int index = 0; index < subsetFilesTrue.Length; index++) { fileLearn.WriteLine(goodImages[subsetFilesTrue[index]].getAllParameters(true)); } for (int index = 0; index < subsetFilesFalse.Length; index++) { fileLearn.WriteLine(badImages[subsetFilesFalse[index]].getAllParameters(false)); } fileLearn.Close(); MLApp.MLApp matlab = new MLApp.MLApp(); string cd = "cd C:\\Users\\anoach\\Desktop\\papa_matlab"; matlab.Execute(cd); //TODO: choose only the algo u need... matlab.Execute("albumLearnPoly5('" + userPath + "');"); matlab.Execute("albumLearnPolyTen('" + userPath + "');"); matlab.Execute("albumLearnPolyTenFive('" + userPath + "');"); matlab.Execute("albumLearnQuadratic('" + userPath + "');"); matlab.Execute("albumLearnRbf1('" + userPath + "');"); matlab.Execute("albumLearnRbf3('" + userPath + "');"); matlab.Execute("albumLearnRbf5('" + userPath + "');"); }
private string Internal_Decide(ImageVector[] filesTrue, ImageVector[] filesFalse, int algo) { int trueAndSelected = 0; int FalseAndNotSelected = 0; int trueButNotSelected = 0; int falseButSelected = 0; string data; MLApp.MLApp matlab = new MLApp.MLApp(); string cd = "cd C:\\Users\\anoach\\Desktop\\papa_matlab"; matlab.Execute(cd); for (int i = 0; i < filesTrue.Length; i++) { if (Internal_DecideImage(matlab, filesTrue[i], algo)) trueAndSelected++; else trueButNotSelected++; } for (int i = 0; i < filesFalse.Length; i++) { if (Internal_DecideImage(matlab, filesFalse[i], algo)) falseButSelected++; else FalseAndNotSelected++; } data = trueAndSelected + "," + trueButNotSelected + "," + falseButSelected + "," + FalseAndNotSelected; return data; }
static void Main(string[] args) { //////////////////////////////////////////////////////////////////// Loading files ///////////////////////////////////////////////////////////////////// // Variables used in matlab //double lambda = 1.5; double num_users = 4; double num_movies = 5; double num_features = 3; // Generate data according with the logic express in Matlab double[,] X = new double[(int)num_movies, (int)num_features]; double[,] Y = new double[(int)num_movies, (int)num_users]; double[,] Theta = new double[(int)num_users, (int)num_features]; double[,] R = new double[(int)num_movies, (int)num_users]; //filling out the matrix X using (TextReader readerX = File.OpenText("C:/Users/laerte/Documents/GitHub/ummatlab/Recommender systems/Data/data_x.txt")) { int i = 0; string line = readerX.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); for (int j = 0; j < (int)num_features; j++) { //Console.Write(temp[j - 1]); X[i, j] = Convert.ToDouble(temp[j]); } line = readerX.ReadLine(); i++; } readerX.Close(); } //filling out the matrix Y using (TextReader readerY = File.OpenText("C:/Users/laerte/Documents/GitHub/ummatlab/Recommender systems/Data/data_y.txt")) { int i = 0; string line = readerY.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); for (int j = 0; j < (int)num_users; j++) { //Console.Write(temp[j - 1]); Y[i, j] = Convert.ToDouble(temp[j]); } line = readerY.ReadLine(); i++; } readerY.Close(); } // Filling out the matrix theta using (TextReader readerTheta = File.OpenText("C:/Users/laerte/Documents/GitHub/ummatlab/Recommender systems/Data/data_theta.txt")) { int i = 0; string line = readerTheta.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); for (int j = 0; j < (int)num_features; j++) { //Console.Write(temp[j - 1]); Theta[i, j] = Convert.ToDouble(temp[j]); } line = readerTheta.ReadLine(); i++; } readerTheta.Close(); } // Filling out the matrix theta using (TextReader readerR = File.OpenText("C:/Users/laerte/Documents/GitHub/ummatlab/Recommender systems/Data/data_r.txt")) { int i = 0; string line = readerR.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); for (int j = 0; j < (int)num_users; j++) { //Console.Write(temp[j - 1]); R[i, j] = Convert.ToDouble(temp[j]); } line = readerR.ReadLine(); i++; } readerR.Close(); } //Reading the file to get the size of lines and columns of R and Y, which will be used in training colloborative filtering int num_movies_init; int num_users_init; using (TextReader readerSize = File.OpenText("C:/Users/laerte/Desktop/Y_training.txt")) { num_movies_init = 0; string line = readerSize.ReadLine(); string[] temp = line.Split('\t'); num_users_init = temp.Length; while (line != null) { line = readerSize.ReadLine(); num_movies_init++; } readerSize.Close(); } //Now we read R and Y from theirs files double[,] Y_training = new double[num_movies_init, num_users_init]; double[,] R_training = new double[num_movies_init, num_users_init]; //reading Y_training using (TextReader readerY = File.OpenText("C:/Users/laerte/Desktop/Y_training.txt")) { int i = 0; string line = readerY.ReadLine(); string[] temp = line.Split('\t'); while (line != null) { for (int j = 0; j < num_users_init; j++) { Y_training[i, j] = Convert.ToDouble(temp[j]); } line = readerY.ReadLine(); i++; } readerY.Close(); } //reading R_training using (TextReader readerR = File.OpenText("C:/Users/laerte/Desktop/R_training.txt")) { int i = 0; string line = readerR.ReadLine(); string[] temp = line.Split('\t'); while (line != null) { for (int j = 0; j < num_users_init; j++) { R_training[i, j] = Convert.ToDouble(temp[j]); } line = readerR.ReadLine(); i++; } readerR.Close(); } // Movie rating file for a user X double[,] my_ratings = new double[num_movies_init, 1]; // make sure that the data will be zero for all the other positions Array.Clear(my_ratings, 0, num_movies_init); using (TextReader reader_movies_ratings = File.OpenText("C:/Users/laerte/Documents/GitHub/ummatlab/Recommender systems/Data/movies_ratings.txt")) { int i = 0; string line = reader_movies_ratings.ReadLine(); while (line != null) { string[] temp = line.Split('\t'); my_ratings[Convert.ToInt32(temp[0]) - 1, 0] = Convert.ToInt32(temp[1]); line = reader_movies_ratings.ReadLine(); i++; } reader_movies_ratings.Close(); } // Movie list file for a user X string[] movie_list = new string[num_movies_init]; using (TextReader reader_movie_list = File.OpenText("C:/Users/laerte/Documents/GitHub/ummatlab/Recommender systems/Data/movie_ids.txt")) { string line = reader_movie_list.ReadLine(); int i = 0; while (line != null) { line = line.Replace((i + 1).ToString() + " ", ""); movie_list[i] = line; line = reader_movie_list.ReadLine(); i++; } reader_movie_list.Close(); } /////////////////////////////////////////////////////////////////////// Matlab calculations ///////////////////////////////////////////////////////////////////// // Create the MATLAB instance MLApp.MLApp matlab = new MLApp.MLApp(); // Change to the directory where the functions are located --- always use the desktop to make tests to avoid problems with pathway matlab.Execute(@"cd C:\Users\laerte\Desktop"); // Calling a function to calculate the parameters to send it to cofiCostFunc object parameters = null; matlab.Feval("generateParams", 1, out parameters, X, Theta); object[] par = parameters as object[]; // Define the output to print the final result for CofiCostFunc //object result = null; // Call the MATLAB function myfunc matlab.Execute("clear all"); // Execute the function in Matlab function to check J // matlab.Feval("cofiCostFunc", 2, out result, (par[0]), Y, R, num_users, num_movies, num_features, lambda); // Checking the gradients //object check = null; //matlab.Feval("checkCostFunction", 0, out check, lambda); // Display result [cost, grad] = costFunctionReg(initial_theta, X, y, lambda); //object[] res = result as object[]; // Print J and grad from CofiCostFunc, which are the returned by this function --- I will commment this part Console.WriteLine("Go to Matlab to do the interactions..."); /* Console.WriteLine("Computing the cost J = " + res[0]); int len = ((double[,])(res[1])).Length; for (int n=0; n < len; n++) { Console.WriteLine("grad = " +((double[,])res[1])[n,0]); } */ // Define the output to print the final result object result_movies_search = null; // Movie recommendations script matlab.Feval("scriptGeneration", 1, out result_movies_search, my_ratings, movie_list, Y_training, R_training); // Wait until fisnih Console.Write("Presse ENTER to close the window"); Console.ReadLine(); // Closing the matblab window //matlab.Quit(); }
public override IOperation Apply() { lock (locker) { var initializationScript = MatlabInitializationScriptParameter.ActualValue; if (!string.IsNullOrEmpty(initializationScript.Value) && !initializationScript.Exists()) throw new FileNotFoundException(string.Format("The initialization script \"{0}\" cannot be found.", initializationScript.Value)); var evaluationScript = MatlabEvaluationScriptParameter.ActualValue; if (string.IsNullOrEmpty(evaluationScript.Value)) throw new FileNotFoundException("The evaluation script in the problem is not set."); if (!evaluationScript.Exists()) throw new FileNotFoundException(string.Format("The evaluation script \"{0}\" cannot be found.", evaluationScript.Value)); string result; if (matLabConnector == null) { Type matlabtype = Type.GetTypeFromProgID("matlab.application.single"); matLabConnector = (MLApp.MLApp)Activator.CreateInstance(matlabtype); matLabConnector.Visible = 0; if (!string.IsNullOrEmpty(initializationScript.Value)) { var directoryName = Path.GetDirectoryName(initializationScript.Value); if (string.IsNullOrEmpty(directoryName)) directoryName = Environment.CurrentDirectory; result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName)); if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result); result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(initializationScript.Value)); if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result); } } if (!changedDirectory) { var directoryName = Path.GetDirectoryName(evaluationScript.Value); if (string.IsNullOrEmpty(directoryName)) directoryName = Environment.CurrentDirectory; result = matLabConnector.Execute(string.Format("cd '{0}'", directoryName)); if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result); changedDirectory = true; } var parameterVector = ParameterVectorParameter.ActualValue; var parameterNames = ParameterNamesParameter.ActualValue; for (int i = 0; i < ProblemSizeParameter.ActualValue.Value; i++) { matLabConnector.PutWorkspaceData(parameterNames[i], "base", parameterVector[i]); } result = matLabConnector.Execute(Path.GetFileNameWithoutExtension(evaluationScript.Value)); if (!string.IsNullOrEmpty(result)) throw new InvalidOperationException(result); string qualityVariableName = QualityVariableParameter.ActualValue.Value; var quality = matLabConnector.GetVariable(qualityVariableName, "base"); if (double.IsNaN(quality)) quality = double.MaxValue; if (double.IsInfinity(quality)) quality = double.MaxValue; QualityParameter.ActualValue = new DoubleValue(quality); return base.Apply(); } }
// Protected implementation of Dispose pattern. protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { // Free any other managed objects here. // matlab.Quit(); matlab = null; } // Free any unmanaged objects here. // disposed = true; }
/*unused variables for poorly timed autofocus method static private long currentSum; static private long prevSum; static private long locMaxSum; static Bitmap bmp;*/ static int initialize() { try { CameraHandler = new SDKHandler(); CameraHandler.LiveViewUpdated += new SDKHandler.StreamUpdate(SDK_LiveViewUpdated); CameraHandler.CameraHasShutdown += SDK_CameraHasShutdown; CameraHandler.SDKObjectEvent += handler_SDKObjectEvent; List<Camera> cameras = CameraHandler.GetCameraList(); Console.WriteLine("List of connected camers:"); foreach (Camera cam in cameras) { Console.WriteLine(cam.Info.szDeviceDescription); } if (cameras.Count > 0) { CameraHandler.OpenSession(cameras[0]); Console.WriteLine("Opened session with camera: " + cameras[0].Info.szDeviceDescription); } else { Console.WriteLine("No camera found. Please plug in camera"); CameraHandler.CameraAdded += handler_CameraAdded; CallEvent(); } CameraHandler.ImageSaveDirectory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "RemotePhoto"); CameraHandler.SetSetting(EDSDK.PropID_SaveTo, (uint)EDSDK.EdsSaveTo.Host); //create a buffer in memory to capture images uint memory_alloc_error = EDSDK.EdsCreateMemoryStream(buffer_size, out frame_stream); img_array = new int[1, 1]; matlab = new MLApp.MLApp(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); return 0; } //MTB Initiailization Protocol INIT: try { m_MTBConnection = new MTBConnection(); //establish a connection to the MTB server } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("Try again?(y/n): "); //connection unsuccessful string command = Console.ReadLine(); switch (command) { case "y": goto INIT; default: return 0; } } // no ID yet m_ID = ""; // create event sink helper class for base events baseEvents = new MTBBaseEventSink(); // connect event handler with helper class baseEvents.MTBErrorEvent += new MTBBaseErrorHandler(OnMtbError); return 1; }
static void initialize() { try { CameraHandler = new SDKHandler(); CameraHandler.LiveViewUpdated += new SDKHandler.StreamUpdate(SDK_LiveViewUpdated); CameraHandler.CameraHasShutdown += SDK_CameraHasShutdown; CameraHandler.SDKObjectEvent += handler_SDKObjectEvent; List<Camera> cameras = CameraHandler.GetCameraList(); Console.WriteLine("List of connected camers:"); foreach (Camera cam in cameras) { Console.WriteLine(cam.Info.szDeviceDescription); } if (cameras.Count > 0) { CameraHandler.OpenSession(cameras[0]); Console.WriteLine("Opened session with camera: " + cameras[0].Info.szDeviceDescription); } else { Console.WriteLine("No camera found. Please plug in camera"); CameraHandler.CameraAdded += handler_CameraAdded; CallEvent(); } CameraHandler.ImageSaveDirectory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "RemotePhoto"); CameraHandler.SetSetting(EDSDK.PropID_SaveTo, (uint)EDSDK.EdsSaveTo.Host); //create a buffer in memory to capture images uint memory_alloc_error = EDSDK.EdsCreateMemoryStream(buffer_size, out frame_stream); img_array = new int[1,1]; matlab = new MLApp.MLApp(); /* Console.WriteLine("Taking photo with current settings..."); CameraHandler.TakePhoto(); CallEvent(); Console.WriteLine("Photo taken and saved"); */ } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
public bool Learn() { // Get list of files in folders string[] filesAll = Testing.GetFilesFromDirectory(allPath).ToArray(); string[] filesTrue = Testing.GetFilesFromDirectory(truePath).ToArray(); if (filesAll.Length <= 0 || filesTrue.Length <= 0) return false; // Make False vector list - All the files in all that are not in true. int index = 0; string[] filesFalse = new string[filesAll.Length - filesTrue.Length]; bool exist; string fn_all, fn_true; for (int i = 0; i < filesAll.Length; i++) { fn_all = filesAll[i].Substring(filesAll[i].LastIndexOf("\\") + 1); exist = false; for (int j = 0; j < filesTrue.Length; j++) { fn_true = filesTrue[j].Substring(filesTrue[j].LastIndexOf("\\") + 1); if (fn_true.Equals(fn_all)) { exist = true; break; } } if (exist) continue; filesFalse[index++] = filesAll[i]; } string csvPath = userPath + "\\Learn.txt"; System.IO.StreamWriter file = new System.IO.StreamWriter(@csvPath, true); // Convert to vector List foreach (string path in filesTrue) { ImageVector vec = new ImageVector(path, null); file.WriteLine(vec.getAllParameters(true)); } foreach (string path in filesFalse) { ImageVector vec = new ImageVector(path, null); file.WriteLine(vec.getAllParameters(false)); } file.Close(); MLApp.MLApp matlab = new MLApp.MLApp(); string cd = "cd C:\\Users\\anoach\\Desktop\\papa_matlab"; string exe = "albumLearn('" + userPath + "');"; matlab.Execute(cd); matlab.Execute(exe); return true; }
private string Internal_Decide(ImageVector[] filesTrue, ImageVector[] filesFalse, int algo) { int trueAndSelected = 0; int FalseAndNotSelected = 0; int trueButNotSelected = 0; int falseButSelected = 0; string data; MLApp.MLApp matlab = new MLApp.MLApp(); string cd = "cd C:\\Program Files\\MATLAB\\R2013a\\bin"; matlab.Execute(cd); for (int i = 0; i < filesTrue.Length; i++) { if (Internal_DecideImage(matlab, filesTrue[i], algo)) trueAndSelected++; else trueButNotSelected++; } for (int i = 0; i < filesFalse.Length; i++) { if (Internal_DecideImage(matlab, filesFalse[i], algo)) falseButSelected++; else FalseAndNotSelected++; } data = trueAndSelected + "," + trueButNotSelected + "," + falseButSelected + "," + FalseAndNotSelected; return data; }
/// <summary> /// Send a array of strings to Matlab. /// </summary> /// <param name="varName"> The unique variable name.</param> /// <param name="strInput"> Passed Array of Data.</param> /// <exception cref="System.RunTime.InteropServices.COMException"> Thrown when matlab is closed and no connection.</exception> public static void sendDataToMatlab(string varName, string[] strInput) { try { matlab.PutWorkspaceData(varName, "base", strInput); // varname, workspace, values } catch (System.Runtime.InteropServices.COMException ex) { matlab = null; } }
/// <summary> /// Start the MATLAB COM Automation Server via a BackgroundWorker. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void matlabStarter_DoWork(object sender, DoWorkEventArgs e) { Instance = new MLApp.MLApp(); }