private Matrice Simulation(Matrice Er, Matrice Vol, Decomposition decompo, int observ) { int n = decompo.L.Colonnes; // nombre de titres Matrice Historique = new Matrice(observ, n); Random rand = new Random(); for (int i = 0; i < observ; i++) { for (int j = 0; j < n; j++) { double p = (double)rand.Next(1, int.MaxValue) / int.MaxValue; Historique[i, j] = Statistique.NormInv(0, 1, p); } } Historique = Historique.Mult(decompo.U); for (int i = 0; i < observ; i++) { for (int j = 0; j < n; j++) { Historique[i, j] = Er[j, 0] + Historique[i, j] * Vol[j, 0]; } } return(Historique); }
/// <summary> /// Returns the matrix of interpolation coefficients. /// </summary> /// <param name="points">Number of points</param> /// <returns>Matrix</returns> public static float[,] GetCoefficients(int points) { // Compute difference coefficient table float fac = Special.Factorial(points); float[,] deltas = new float[points, points]; float h, delta; int j, k; // do job for (j = 0; j < points; j++) { h = 1.0f; delta = j; for (k = 0; k < points; k++) { deltas[j, k] = h / Special.Factorial(k); h *= delta; } } // matrix invert deltas = Matrice.Invert(deltas); //// rounding //for (j = 0; j < points; j++) // for (k = 0; k < points; k++) // deltas[j, k] = (Math.Round(deltas[j, k] * fac, MidpointRounding.AwayFromZero)) / fac; return(deltas); }
/// <summary> /// Initializes power iteration. /// </summary> /// <param name="A">Matrix</param> /// <param name="iterations">Number of iterations</param> public Power(float[,] A, int iterations = 10) { if (!Matrice.IsSquare(A)) { throw new Exception("The matrix must be square"); } // eigenvalue power algorithm: int n = A.GetLength(0); this.v = Matrice.Rand(n); float[] w; float beta; // power iteration: for (int i = 0; i < iterations; i++) { // formula: // v[j] = (v[j-1] * A) / || v[j-1] * A || w = Matrice.Dot(v, A); beta = Matrice.Norm(w); v = Matrice.Div(w, beta); } return; }
public void TestMultiplyMatriceNOK() { int[,] matrice = new int[, ] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int[,] matrice2 = new int[, ] { { 1, 2, 3 }, { 4, 5, 6 } }; int[,] matriceTest = new int[, ] { { 30, 36, 42 }, { 66, 81, 96 }, { 102, 126, 150 } }; try { Matrice m1 = new Matrice(matrice); Matrice m2 = new Matrice(matrice2); Matrice mTest = m1 * m2; Assert.Fail(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(MatriceException)); } }
/// <summary> /// Backward sine transform. /// </summary> /// <param name="B">Array</param> /// <returns>Array</returns> public float[] Backward(float[] B) { int N = B.Length; float[,] U = SineTransform.Matrix(N); return(Matrice.Dot(B, U.Transponate())); }
private void BtnTriangularite_Click(object sender, RoutedEventArgs e) { try { Matrice matriceA = CreerMatriceA(Convert.ToInt32(LignesA.Text), Convert.ToInt32(ColonnesA.Text)); bool stricte = Stricte.IsChecked.Value; int choix; string reponse = "Non"; if (radioButton1.IsChecked.Value) { choix = 0; } else if (radioButton2.IsChecked.Value) { choix = 1; } else { choix = 2; } bool m = matriceA.EstTriangulaire(choix, stricte); if (m == true) { reponse = "Oui"; } resultatsTxt.Text = "Triangulaire tel que spécifié? : " + reponse; } catch (Exception ex) { resultatsTxt.Text = ""; MessageBox.Show(ex.Message); } }
/// <summary> /// Fait la décomposition L de la matrice /// </summary> /// <param name="gauche">La matrice dans l'éditeur</param> /// <returns>La matrice inférieure L</returns> static public Matrice DecompositionL(Matrice gauche) { float[,] L = new float[gauche.NbLignes, gauche.NbColonnes]; float[,] tableauGauche = gauche.DataMatrice; float déterminant = Déterminant(new Matrice(tableauGauche)); if (déterminant != 0 && gauche.NbColonnes == 3 && gauche.NbLignes == 3) { float[] diviseurs = new float[3]; diviseurs[0] = tableauGauche[1, 0] / tableauGauche[0, 0]; diviseurs[1] = tableauGauche[2, 0] / tableauGauche[0, 0]; diviseurs[2] = (tableauGauche[2, 1] - diviseurs[1] * tableauGauche[0, 1]) / (tableauGauche[1, 1] - diviseurs[0] * tableauGauche[0, 1]); for (int i = 0; i < gauche.NbColonnes; i++) { for (int j = 0; j < gauche.NbLignes; j++) { if (i == j) { L[i, j] = 1; } else if (i < j) { L[i, j] = 0; } } } L[1, 0] = diviseurs[0]; L[2, 0] = diviseurs[1]; L[2, 1] = diviseurs[2]; } return(new Matrice(L)); }
/// <summary> /// Initializes eigenvalue decomposition. /// </summary> /// <param name="A">Square matrix</param> /// <param name="eps">Epsilon [0, 1]</param> public EVD(float[,] A, float eps = 1e-16f) { if (!Matrice.IsSquare(A)) { throw new Exception("The matrix must be square"); } this.n = A.GetLength(0); this.Re = new float[n]; this.Im = new float[n]; this.eps = Maths.Float(eps); // for symmetric matrices eigen-value decomposition // without Hessenberg form. if (Matrice.IsSymmetric(A)) { hessenberg = Jagged.Zero(n, n); matrices = Jagged.ToJagged(A); tred2(); // Tridiagonalize. tql2(); // Diagonalize. } // with Hessenberg form. else { matrices = Jagged.Zero(n, n); hessenberg = Jagged.ToJagged(A); orthogonal = new float[n]; orthes(); // Reduce to Hessenberg form. hqr2(); // Reduce Hessenberg to real Schur form. } }
/// <summary> /// Le déterminant d'une matrice 2X2 /// </summary> /// <param name="gauche">La matrice à gauche dans l'éditeur</param> /// <returns>Le déterminant</returns> static public float Déterminant2X2(Matrice gauche) { float déterminant; déterminant = gauche[0, 0] * gauche[1, 1] - gauche[0, 1] * gauche[1, 0]; return(déterminant); }
/// <summary> /// Réduit la matrice d'une ligne et d'une colonne /// </summary> /// <param name="ligne">La ligne à réduire de la matrice</param> /// <param name="colonne">La colonne è réduire de la matrice</param> /// <param name="matrice">La matrice à réduire</param> /// <returns>La matrice réduite</returns> public static Matrice Réduire(int ligne, int colonne, Matrice matrice) { float[,] resultat = new float[matrice.NbLignes - 1, matrice.NbColonnes - 1]; float[,] tableauMatrice = matrice.DataMatrice; for (int i = 0, j = 0; i < tableauMatrice.GetLength(0); i++) { if (i == ligne) { continue; } for (int k = 0, u = 0; k < tableauMatrice.GetLength(1); k++) { if (k == colonne) { continue; } resultat[j, u] = tableauMatrice[i, k]; u++; } j++; } Matrice matriceRéduite = new Matrice(resultat); return(matriceRéduite); }
/// <summary> /// /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="win"></param> /// <param name="max_dis"></param> /// <param name="weight"></param> /// <param name="apply_median"></param> /// <returns></returns> private float[,] disparity_estimator(float[,] left, float[,] right, int win, int max_dis, float weight, bool apply_median = false) { int x = left.GetLength(1); int y = left.GetLength(0); int z = 3; var gradient = new float[] { 1, -1 }; var left_x = Matrice.Conv(left, gradient, Direction.Horizontal); var left_y = Matrice.Conv(left, gradient, Direction.Vertical); var right_x = Matrice.Conv(right, gradient, Direction.Horizontal); var right_y = Matrice.Conv(right, gradient, Direction.Vertical); var im_l = new float[][, ] { left, left_x, left_y }; var im_r = new float[][, ] { right, right_x, right_y }; var even_win = Maths.IsEven(win) ? win : win + 1; var disparity = disparity_processor(im_l, im_r, even_win, max_dis, weight, x, y, z); if (apply_median) { disparity = Matrice.Morph(disparity, even_win, even_win, even_win / 2, even_win / 2); } return(disparity); }
/// <summary> /// Transformed domain recursive filter (vertical). /// </summary> /// <param name="F">Input signal</param> /// <param name="D">Difference</param> /// <param name="sigma">Sigma</param> internal static void tdrf_v(Complex32[,] F, Complex32[,] D, float sigma) { // params float a = Maths.Exp(-Maths.Sqrt2 / sigma); Complex32[,] V = Matrice.Pow(a, D); int h = F.GetLength(0); int w = F.GetLength(1); int i, j; // Left -> Right filter. for (i = 1; i < h; i++) { for (j = 0; j < w; j++) { F[i, j] = F[i, j] + V[i, j] * (F[i - 1, j] - F[i, j]); } } // Right -> Left filter. for (i = h - 2; i >= 0; i--) { for (j = 0; j < w; j++) { F[i, j] = F[i, j] + V[i + 1, j] * (F[i + 1, j] - F[i, j]); } } return; }
/// <summary> /// Transformed domain recursive filter (horizontal). /// </summary> /// <param name="F">Input signal</param> /// <param name="D">Difference</param> /// <param name="sigma">Sigma</param> internal static void tdrf_h(float[,] F, float[,] D, float sigma) { // params float a = (float)Math.Exp(-Math.Sqrt(2) / sigma); float[,] V = Matrice.Pow(a, D); int h = F.GetLength(0); int w = F.GetLength(1); int i, j; // Left -> Right filter. for (i = 0; i < h; i++) { for (j = 1; j < w; j++) { F[i, j] = F[i, j] + V[i, j] * (F[i, j - 1] - F[i, j]); } } // Right -> Left filter. for (i = 0; i < h; i++) { for (j = w - 2; j >= 0; j--) { F[i, j] = F[i, j] + V[i, j + 1] * (F[i, j + 1] - F[i, j]); } } return; }
/// <summary> /// Domain transform filter. /// </summary> /// <param name="I">Input signal</param> /// <param name="sigma_s">High sigma</param> /// <param name="sigma_r">Low sigma</param> /// <param name="iterations">Number of iterations</param> internal static void domainfilter(Complex32[] I, float sigma_s, float sigma_r, int iterations = 3) { // params int h = I.GetLength(0); float sigma_H_i; int i; // get differences Complex32[] dIcdy = Matrice.Diff(I, 1); // shift patterns Complex32[] dIdy = new Complex32[h]; for (i = 1; i < h; i++) { dIdy[i] = Maths.Abs(dIcdy[i - 1]); } // sigma patterns and result image for (i = 0; i < h; i++) { dIdy[i] = 1 + sigma_s / sigma_r * dIdy[i]; } // iterations for (i = 0; i < iterations; i++) { sigma_H_i = sigma_s * Maths.Sqrt(3) * Maths.Pow(2, (iterations - (i + 1))) / Maths.Sqrt(Maths.Pow(4, iterations) - 1); // 1D filter tdrf(I, dIdy, sigma_H_i); } return; }
private void BtnProduitScalaire_Click(object sender, RoutedEventArgs e) { try { if (Scalaire.Text != "") { Matrice matriceA = CreerMatriceA(Convert.ToInt32(LignesA.Text), Convert.ToInt32(ColonnesA.Text)); resultatsTxt.Text = "Le produit de A par le scalaire " + Scalaire.Text + " est : \r\n"; resultatsTxt.Text += matriceA.FaireProduitScalaire(Convert.ToInt32(Scalaire.Text)).AfficheMatrice(); } else { resultatsTxt.Text = ""; MessageBox.Show("Veuillez entrer un scalaire"); } } catch (Exception ex) { if (ex is FormatException) { resultatsTxt.Text = ""; MessageBox.Show("Erreur de conversion, vérifier les dimensions"); } else { resultatsTxt.Text = ""; MessageBox.Show(ex.Message); } } }
/// <summary> /// Apply filter. /// </summary> /// <param name="data">Matrix</param> public void Apply(Complex32[,] data) { // forward pyramid transform Complex32[][,] pA = lap.Forward(data); int r = data.GetLength(0), c = data.GetLength(1); int nlev = pA.Length - 1, i, j; for (i = 0; i < nlev; i++) { pA[i] = Matrice.Mul(pA[i], 1.0 + this.factor); } // backward pyramid transform Complex32[,] dummy = lap.Backward(pA); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { data[i, j] = dummy[i, j]; } } return; }
private void BtnProduitMatricielFin_Click(object sender, RoutedEventArgs e) { try { Matrice matriceA = CreerMatriceA(Convert.ToInt32(LignesA.Text), Convert.ToInt32(ColonnesA.Text)); Matrice matriceB = CreerMatriceB(Convert.ToInt32(LignesB.Text), Convert.ToInt32(ColonnesB.Text)); Matrice matriceC; int a = 0; if (LignesC.Text != "" && ColonnesC.Text != "") { matriceC = CreerMatriceC(Convert.ToInt32(LignesC.Text), Convert.ToInt32(ColonnesC.Text)); resultatsTxt.Text = "A x (B x C) = \r\n"; resultatsTxt.Text += (matriceA.FaireProduitMatricielParFin(out a, matriceB, matriceC)).AfficheMatrice(); } else { resultatsTxt.Text = "A x B= \r\n"; resultatsTxt.Text += (matriceA.FaireProduitMatriciel(out a, matriceB)).AfficheMatrice(); } resultatsTxt.Text += "Nombre de produits effectues : " + a; } catch (Exception ex) { resultatsTxt.Text = ""; MessageBox.Show(ex.Message); } }
/// <summary> /// Forward sine transform. /// </summary> /// <param name="A">Array</param> /// <returns>Array</returns> public float[] Forward(float[] A) { int N = A.Length; float[,] U = SineTransform.Matrix(N); return(Matrice.Dot(A, U)); }
/// <summary> /// Initializes the Gram-Schmidt orthogonalization process. /// </summary> /// <param name="A">Square matrix</param> public GramSchmidt(float[,] A) { if (!Matrice.IsSquare(A)) { throw new Exception("The matrix must be square"); } // UMapx.NET // gram-schmidt result matrix: n = A.GetLength(0); q = new float[n, n]; int i, j; for (j = 0; j < n; j++) { u = Matrice.GetCol(A, j); // get j-column of matrix A, v2 = u; // copy this column for the second Matrice. for (i = 0; i < j; i++) { v1 = Matrice.GetCol(q, i); // get i-column of matrix Q u = Matrice.Sub(u, GramSchmidt.Proj(v1, v2)); // calculate: u - proj'<v1, v2>, // where ' - means transponate operator for projection. } q = Matrice.SetCol(q, Matrice.Div(u, Matrice.Norm(u)), j); // set j-column of matrix Q. } return; }
/// <summary> /// Returns the window function. /// </summary> /// <param name="frameSize">Window size</param> /// <returns>Array</returns> public override float[] GetWindow(int frameSize) { float t = (frameSize - 1) / 2.0f; float[] x = Matrice.Compute(-t, t, 1); return(this.Function(x, frameSize)); }
//System.Media.SoundPlayer playerexplozie, playergameover, playernewgame, playeraplauze; public Form1() { InitializeComponent(); M = new Matrice(); img = new Image[8]; imgmic = new Image[8]; P = new PictureBox[9, 9]; r = new Random(); t = new Timer(); t.Interval = 100; //100 t.Tick += t_Tick; auto_trigger = new Timer(); auto_trigger.Interval = 100; auto_trigger.Tick += auto_trigger_Tick; xclicked = yclicked = -1; scor = 0; xrestant = yrestant = tiprestant = -1; disableclick = true; //playerexplozie = new System.Media.SoundPlayer("explosion.wav"); //playergameover = new System.Media.SoundPlayer("gameover.wav"); //playernewgame = new System.Media.SoundPlayer("gametime.wav"); //playeraplauze = new System.Media.SoundPlayer("applause.wav"); //sunet = true; InitializarePanel(); IncarcaPoze(); PunePozeInitiale(); //playernewgame.Play(); }
// Méthode calculant la VaR historique public override Tuple <double, double> Calcul() { double VaR_result = 0; double Cvar_result = 0; int position = 0; if (Math.Floor(alpha * Actions.Lignes) == alpha * Actions.Lignes) { position = (int)(alpha * Actions.Lignes); } else { position = (int)Math.Floor(alpha * Actions.Lignes) + 1; } rendements = new Matrice(Actions.Lignes - 1, Actions.Colonnes); double[] VaR_actif = new double[Actions.Colonnes]; double[] Cvar_actif = new double[Actions.Colonnes]; // Calcul des VaR individuelles for (int j = 0; j < Actions.Colonnes; j++) { for (int i = 1; i < Actions.Lignes; i++) { rendements[i - 1, j] = (Actions[i, j] - Actions[i - 1, j]) / Actions[i - 1, j]; } List <double> rendement_tri = new List <double>(); for (int i = 0; i < Actions.Lignes - 1; i++) { rendement_tri.Add(rendements[i, j]); } rendement_tri.Sort(); VaR_actif[j] = rendement_tri[position - 1]; // On récupére la VaR de l'actif seul; -1 car le tableau est indexé à 0 Cvar_actif[j] = CalculCvarFromSorted(rendement_tri); VaR_result += VaR_actif[j] * VaR_actif[j] * CompanyTab[j].Weight * CompanyTab[j].Weight; Cvar_result += Cvar_actif[j] * Cvar_actif[j] * CompanyTab[j].Weight * CompanyTab[j].Weight; } ; // Calcul des corrélations entre les actifs for (int j = 0; j < Actions.Colonnes; j++) { for (int k = j + 1; k < Actions.Colonnes; k++) { // Corrélation entre l'entreprise j et l'entreprise k VaR_result += 2 * Statistique.Correlation(rendements, j, k) * VaR_actif[j] * CompanyTab[j].Weight * VaR_actif[k] * CompanyTab[k].Weight; Cvar_result += 2 * Statistique.Correlation(rendements, j, k) * Cvar_actif[j] * CompanyTab[j].Weight * Cvar_actif[k] * CompanyTab[k].Weight; } } return(new Tuple <double, double> (-Math.Sqrt(VaR_result), -Math.Sqrt(Cvar_result))); }
/// <summary> /// /// </summary> /// <param name="v"></param> private void hmatx(float[] v) { // [1] Alston S. Householder, "Unitary Triangularization of a Nonsymmetric Matrix", // Journal of the ACM 5, 339-242, 1958; // [2] G. W. Stewart, Matrix Algorithms: Volume 1: Basic Decompositions, SIAM, xix+458, 1998. // // Get Householder vector: float[] w = Matrice.Householder(v); // Get Householder matrix: int n = w.Length, i, j; float[] z; this.matrices = new float[n][]; // M = I - w * w': for (i = 0; i < n; i++) { // eye vector z = new float[n]; z[i] = 1.0f; for (j = 0; j < n; j++) { z[j] -= w[i] * w[j]; } matrices[i] = z; } return; }
/// <summary> /// Gère les calculs pour résoudre les SEL /// </summary> public void Calculer() { Matrice résultat = null; Matrice résultatU = null; string équation = ""; switch (opérationActive) { case OpérationsSEL.GAUSS: résultat = Matrice.MéthodeGauss(new Matrice(scriptMatriceSEL.GetDataMatrice)); équation = Matrice.ÉquationGauss(new Matrice(résultat.DataMatrice)); scriptRésultatGauche.AfficherRésultat(résultat); scriptRésultatÉquation.AfficherRésultat(équation); break; case OpérationsSEL.INVERSE: résultat = Matrice.InverseSEL(new Matrice(scriptMatriceSEL.GetDataMatrice)); scriptRésultatGauche.AfficherRésultat(résultat); break; case OpérationsSEL.FACTORISATION: résultat = Matrice.DecompositionL(new Matrice(scriptMatriceSEL.GetDataMatrice)); résultatU = Matrice.DecompositionU(new Matrice(scriptMatriceSEL.GetDataMatrice)); scriptRésultatGauche.AfficherRésultat(résultat); scriptRésultatU.AfficherRésultat(résultatU); break; } }
//Retourne la transposé d'une matrice protected static void Transpose() { int matrice1, indMat1; Matrice matriceTransp; Console.WriteLine(""); Console.WriteLine("Pour quelle matrice souhaiter vous retourner la transposée?"); matrice1 = Int32.Parse(Console.ReadLine()); if (matrice1 > indexMatrice || matrice1 <= 0) { Console.Clear(); Console.WriteLine("Erreur, cette matrice n'existe pas"); } else { indMat1 = matrice1 - 1; matriceTransp = new Matrice(listeMatrice[indMat1].NbCol, listeMatrice[indMat1].NbRow); matriceTransp = listeMatrice[indMat1].Transposee; Console.Clear(); Console.WriteLine("La transposée de la matrice #{0} est la suivante: ", matrice1); matriceTransp.DisplayMatrice(); } }
//Ajout d'un système protected static void AjouterSysteme() { Systeme newSysteme; int n; //Saisit des paramètre de la matrice Console.WriteLine(""); Console.WriteLine("Veuillez entrer le N du système"); n = Int32.Parse(Console.ReadLine()); Matrice newMatriceA = new Matrice(n, n); Matrice newMatriceB = new Matrice(n, 1); //On remplit les matrices du nouveau système newMatriceA.RemplirMatrice(0); newMatriceB.RemplirMatrice(1); newSysteme = new Systeme(newMatriceA, newMatriceB, n); //Ajout du systeme à la liste des Systemes listeSysteme[indexSysteme] = newSysteme; indexSysteme++; Console.Clear(); Console.WriteLine("Le système #{0} a été créée", indexSysteme); }
//Retourne la comatrice d'une matrice protected static void Comatrice() { int matrice1, indMat1; Matrice comatrice; Console.WriteLine(""); Console.WriteLine("Pour quelle matrice souhaiter vous retourner la comatrice?"); matrice1 = Int32.Parse(Console.ReadLine()); if (matrice1 > indexMatrice || matrice1 <= 0) { Console.Clear(); Console.WriteLine("Erreur, cette matrice n'existe pas"); } else { indMat1 = matrice1 - 1; if (!listeMatrice[indMat1].EstCarre) { Console.Clear(); Console.WriteLine("Erreur, la matrice #{0} doit être carré pour pouvoir calculer sa comatrice", matrice1); } else { comatrice = new Matrice(listeMatrice[indMat1].NbRow, listeMatrice[indMat1].NbCol); comatrice = listeMatrice[indMat1].CoMatrice; Console.Clear(); Console.WriteLine("La comatrice de la matrice #{0} est la suivante: ", matrice1); comatrice.DisplayMatrice(); } } }
//Produit scalaire d'une matrice protected static void ProduitScalaire() { int matrice1, indMat1; double scalaire; //Saisit de la matrice a multiplier Console.WriteLine(""); Console.WriteLine("Quel matrice vouler vous multiplier par un scalaire?"); matrice1 = Int32.Parse(Console.ReadLine()); indMat1 = matrice1 - 1; if (matrice1 > indexMatrice || matrice1 <= 0) { Console.Clear(); Console.WriteLine("Erreur, cette matrice n'existe pas"); } else { //Saisit du scalaire Console.WriteLine(""); Console.WriteLine("Veuiller saisir le scalaire par lequel la matrice sera multiplié?"); scalaire = Double.Parse(Console.ReadLine()); Matrice resultat = new Matrice(listeMatrice[indMat1].NbRow, listeMatrice[indMat1].NbCol); resultat = listeMatrice[indMat1].FaireProduitScalaire(scalaire); Console.Clear(); Console.WriteLine("Voici le résultat de la multiplication de la matrice #{0} et du scalaire {1} : ", matrice1, scalaire); resultat.DisplayMatrice(); } }
static int indexSysteme = 3; //a cause des matrices deja créé static void Main(string[] args) { //On initialise des matrices de départs de différent format de manière de ne pas avoir a les créer a toute les fois pour les tests Matrice mat1 = new Matrice(1); Matrice mat2 = new Matrice(2); Matrice mat3 = new Matrice(3); Matrice mat4 = new Matrice(4); Matrice mat5 = new Matrice(5); //On initialise des systeme dequation de départ Systeme sys1 = new Systeme(1); Systeme sys2 = new Systeme(2); Systeme sys3 = new Systeme(3); listeMatrice[0] = mat1; listeMatrice[1] = mat2; listeMatrice[2] = mat3; listeMatrice[3] = mat4; listeMatrice[4] = mat5; listeSysteme[0] = sys1; listeSysteme[1] = sys2; listeSysteme[2] = sys3; NavigationMenu(); }
public static Matrice SaisirMatrice() { Matrice m = null; List <int[]> build = new List <int[]>(); int[] previousLine = null; while (SaisirMatriceLigne(build, previousLine)) { if (build.Count > 0) { previousLine = build.Last(); } } int[,] matrice = new int[build.Count, build.First().Length]; matrice.Parcourir((i, j) => { matrice[i, j] = build[i][j]; }); m = new Matrice(matrice); Console.WriteLine("Vous avez saisie la matrice suivante :"); Console.WriteLine(m); return(m); }
private static void CalculMatrice(Bitmap bitmap, Matrice m, int brillance, double contraste) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new Exception("le format de l'image n'est pas en 32bppArgb !"); //calcul du bord qu'il faut rajouter à l'image pour appliquer la matrice int n = (int)((Math.Sqrt(m.tableau.Length) - 1) / 2); //on crée un bord de n pixel sur l'image avec effet mirroir Bitmap imageMirror = CreateBitmapWithMirrorBorder(bitmap, n); //Grâce aux variables locales, on évite des instructions IL supplémentaires //par exemple la mise de l'adresse du champ dans la pile d'évaluation de la méthode int facteur = m.facteur;//division int moffset = m.offset;//ajout int widthMirror = imageMirror.Width; int heightMirror = imageMirror.Height; int width = bitmap.Width; int height = bitmap.Height; int tailleMatrice = m.tableau.Length; unsafe { //utilisation tableau sur la pile int* tabParam = stackalloc int[tailleMatrice]; //initialisation du tableau de paramètres for (int i = 0; i < tailleMatrice; i++) tabParam[i] = m.tableau[i] * 256 / facteur; BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); BitmapData bmpDataMirror = imageMirror.LockBits(new Rectangle(0, 0, widthMirror, heightMirror), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); //pointeur sur l'image fournie (déplacement par 4 octets) int* newPixel = (int*)(void*)bmpData.Scan0; //pointeur sur l'image avec bords en miroir (déplacement par octets) byte* mPixel = (byte*)(void*)bmpDataMirror.Scan0; int r, g, b;//composantes rouge, verte et bleue int loc;//localisation du pointeur int cst2 = 2 * n + 1;//longueur d'une ligne int indice;//indice dans le tableau int tab;//stockage intermédiaire du tableau int indicemax;// indice maximum dans le tableau avant le passage à la ligne dans la matrice //Zone initiale par rapport à la position du pointeur sur l'image avec miroir int locIni = (1 - widthMirror) * (4 * n); //Zone maximum par rapport à la position du pointeur sur l'image avec miroir int locMax = (widthMirror + 1) * (4 * n); //incrémentation de la localisation par rapport à la position du pointeur int locIncrement = (widthMirror - (cst2 + 1)) * 4; //incrément pour le déplacement du pointeur sur l'image avec miroir int mPixelIncrement = (2 * n * 4); //on positionne le pointeur sur l'image avec bords en miroir mPixel += (widthMirror + 1) * (n * 4); //calcul de l'adresse maximum possible du pointeur sur l'image fournie //L'adresse ne change pas car les données de l'image ne sont pas en zone gérée //(donc non affecté par le garbage collector) int AdressMax = (int)newPixel + (height * width * 4); //On économise l'incrémentation d'une variable locale simplement en comparant l'adressage. while ((int)newPixel < AdressMax) { //parcours de la hauteur de l'imae for (int x = 0; x < width; x++) { //parcours de la largeur de l'image //initialisations à chaque pixel r = 0; g = 0; b = 0; indice = 0; loc = locIni; do { //calcul de l'indice maximum de la matrice avant de franchir une nouvelle ligne indicemax = indice + cst2; do { //parcours d'une ligne de matrice tab = tabParam[indice]; b += mPixel[loc] * tab; //composante bleue g += mPixel[loc + 1] * tab; //composante verte r += mPixel[loc + 2] * tab; //composante rouge loc += 4; } while (indice++ < indicemax); //on passe à la ligne suivante de la matrice loc += locIncrement; } while (loc < locMax); //calcul des composantes r = (r >> 8) + moffset; b = (b >> 8) + moffset; g = (g >> 8) + moffset; //Application de la contraste et de la brillance r = (int)((r + brillance) * contraste); b = (int)((b + brillance) * contraste); g = (int)((g + brillance) * contraste); //bornage des composantes r = (r < 0) ? 0 : (r > 255)? 255 : r; b = (b < 0) ? 0 : (b > 255) ? 255 : b; g = (g < 0) ? 0 : (g > 255) ? 255 : g; //on garde la transparence et on évite de placer 255 sur la pile newPixel[0] = mPixel[3] << 24 | r << 16 | g << 8 | b; //deplacement des pointeurs vers le prochain pixel newPixel++; mPixel += 4; } mPixel += mPixelIncrement;//Saut du pointeur de l'image aux bords en miroir } bitmap.UnlockBits(bmpData); imageMirror.UnlockBits(bmpDataMirror); } imageMirror.Dispose(); }