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); }
private void button1_Click(object sender, EventArgs e) { matlab.Visible = 0; String cmd_str2 = "theta=linspace(0,360,36);" + "XX = 1 * cos(theta * pi / 180);" + "YY = 1 * sin(theta * pi / 180);" + "ZZ = linspace(0, 10, 36);" + "X =[]; Y =[]; Z =[];" + "hold on;" + " grid on;" + "for i = 1:10" + "Z(i,:) = i * ones(length(ZZ), 1);" + "Y(i,:) = i * YY';" + "X(i,:) = XX'/i;" + "plot3(X(i,:), Y(i,:), Z(i,:));" + " end;" + " view(45, 30);"; matlab.Execute(cmd_str2); }
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"; }
/// <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; } }
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 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 Matlab() { matlab.Visible = 0; ex0 = matlab.Execute("rosinit('192.168.1.161');"); //CHANGE IP!!!!!, CHECK THE IP OF THE OTHER LISTENER ex1 = matlab.Execute("chatpub = rospublisher('/turtle', 'std_msgs/String');"); ex2 = matlab.Execute("msg = rosmessage(chatpub);"); }
/// <summary> /// Sets the Transfer Function in Matlab /// </summary> public void setTFtoMatlabEnviroment() { // Puts the num en den in the Matlab enviroment MWinstance.PutWorkspaceData("num", "base", num); MWinstance.PutWorkspaceData("den", "base", den); //Create the transfer function MWinstance.Execute(STR_SysTfnumDen); }
public PanelFondo() { //al correr el programa abro el modelo en simulink ubicado en C:/matlabfunctions/pidtest.slx y seteo ov en 2 InitializeComponent(); MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute(@"cd C:\matlabfunctions"); matlab.Execute("open_system('pidtest')"); matlab.Execute("set_param('pidtest/Constant', 'Value', '2')"); btnauto.BackColor = c1; }
/// <summary> /// Initialize the COM Automation Server. /// </summary> public static void InitializeMatlab() { MatlabServer = new MLApp.MLApp(); // set directory var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\MATLAB"; MatlabServer.Execute(@"cd('" + dir + @"');"); // delete all variables in memory and clear screen MatlabServer.Execute(@"clear;clc;"); }
/// <summary> /// Removes the variable from Matlab Workspace along with the timespace. /// </summary> /// <remarks> Only called when the log is editted.</remarks> /// <param name="varName">The name of the variable in Matlab.</param> public static void removeMatlabVariable(string varName) { try { matlab.Execute("clear " + varName + "Time"); matlab.Execute("clear " + varName); } catch { } }
static void Main(string[] args) { NamedPipeClientStream pipeclient = new NamedPipeClientStream(".", "HarryThePipe", PipeDirection.InOut); Console.WriteLine("Connecting to the server....."); pipeclient.Connect(); Console.WriteLine("Server Connected"); StreamBytes clientStream = new StreamBytes(pipeclient); MLApp.MLApp matlab = new MLApp.MLApp(); matlab.Execute(@"cd C:\Users\Sam\Desktop\Proj"); matlab.Execute("PanelFunction"); while (pipeclient.IsConnected) { Console.WriteLine("."); //Read Variables Thread.Sleep(100); double cellAlpha = clientStream.ReadBytes(); double cellBeta = clientStream.ReadBytes(); double cellGamma = clientStream.ReadBytes(); double cellDelta = clientStream.ReadBytes(); double cellMu = clientStream.ReadBytes(); double cellTau = clientStream.ReadBytes(); Console.WriteLine("Received from Server: " + cellAlpha + "," + cellBeta + "," + cellGamma + "," + cellDelta + "," + cellMu + "," + cellTau); Object resultOfMatlab = null; matlab.Feval("PanelFunction", 3, out resultOfMatlab, cellAlpha, cellBeta, cellGamma, cellDelta, cellMu, cellTau); object[] res = resultOfMatlab as object[]; double powerOutput = Convert.ToDouble(res[0]); double voltageOutput = Convert.ToDouble(res[1]); double currentOutput = Convert.ToDouble(res[2]); //Send Message to Server clientStream.WriteBytes(powerOutput); pipeclient.Flush(); clientStream.WriteBytes(voltageOutput); pipeclient.Flush(); clientStream.WriteBytes(currentOutput); pipeclient.Flush(); Console.WriteLine("WrtieBytes Passed"); pipeclient.Flush(); } pipeclient.Close(); }
public void load(string filename) { using ( Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TestWpfSVM.MatlabCodes." + filename)) { using (StreamReader sr = new StreamReader(stream)) { string content = sr.ReadToEnd(); sr.Close(); matlab.Execute(content); } } }
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; } }
/// <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(); }
public void pulseFunction() { matlab.Execute(@"cd 'C:\Users\Anna Birgersson\Documents\MATLAB\Shimmer Matlab Instrument Driver v2.6'");//\ShimmerBiophysicalProcessingLibrary_Rev_0_10.jar"); while (isRunning) { // Define the output object result = null; // Call the MATLAB function myfunc matlab.Feval("ecgtoheartrate", 1, out result, "7", 15, "testdata.dat"); // Display result object[] res = result as object[]; Console.Write("\r{0} ", res[0]); //TODO: Uppdaterar label och skriver pulsen Dispatcher.Invoke(() => { pulseLabel.Content = "Pulse: " + res[0]; }); int i; i = Convert.ToInt32(res[0]); allPulses.Add(i); // add pulse to allPulse list timePulses.Add(Convert.ToInt32(sw.ElapsedMilliseconds) / 1000); // lista med tid } }
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); }
private RecognitionProvider() { _matlab = new MLApp.MLApp(); // Change to the directory where the function is located _matlab.Execute(@"cd " + AppDomain.CurrentDomain.BaseDirectory + "ReconScript/"); }
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); }
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 static double[] RecognizeSketch(string filename, out int predictedClass) { object result = null; predictedClass = 0; m_Matlab.Execute(@"cd '" + m_Pwd + "\\Data'"); m_Matlab.Feval("predictClass", 2, out result, filename); object[] res = result as object[]; if (res == null || res.Length < 2) { return(null); } //Results //1=class, 2=imp, 3=inh predictedClass = (int)((double)res[0]); double[] probs = new double[3]; double[,] p = (double[, ])res[1]; for (int i = 0; i < p.GetLength(1); i++) { probs[i] = p[0, i]; } return(probs); }
// 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); }
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. }
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); } }
// 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 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 OdeSolver() { new Thread(() => { _matlab = new MLApp.MLApp(); _matlab.Execute($"cd {Directory.GetCurrentDirectory()}\\Matlab"); }).Start(); }
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]); }
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 Form1_Load(object sender, EventArgs e) { string[] ports = SerialPort.GetPortNames(); Array.Sort(ports); comboBox1.Items.AddRange(ports); comboBox1.SelectedIndex = comboBox1.Items.Count > 0 ? 0 : -1; if (ports.Length == 0) { this.btnOpenPort.Enabled = false; } comboBox2.SelectedIndex = 0; matlab.Visible = 1; matlab.Execute("hold on;"); }
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 object PlotGraphHistory(IGraph graph, string msg = "") { var graphHistory = graph.GetEdgesHistory(); Matlab.Execute($"cd '{_pathToPlotFunctionFolder}'"); Matlab.Feval("plot_graph_history", 0, out var figure, graphHistory.Source.ToArray(), graphHistory.Target.ToArray(), graphHistory.Weigth.ToArray(), graphHistory.Marker.ToArray(), graph.Directed, msg); return(figure); }
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 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 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; }
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 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); }
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(); }
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; }
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 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; }
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(); } }
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(); }
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; }
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) { /////////////////////////////////////// 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 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 + "');"); }
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(); }