}//Método para idspotify x título y artista
 private List<String> getIdsSpotify(List<String> listaIndices)
 {
     List<String> getIdsSpotify = new List<String>(); ModeloSimilitudEntities db = new ModeloSimilitudEntities();
     List<canciones> musicas = db.canciones.ToList();
     foreach (String indice in listaIndices)
     {
         getIdsSpotify.Add((musicas[Int32.Parse(indice)]).id_spotify);
     }
     return getIdsSpotify;
 }//Similar al 1ero pero trae una lista
        private List<String> GetSimilaresDatabaseKNN(List<Double> descriptoresEntrada)
        {
            ModeloSimilitudEntities db=new ModeloSimilitudEntities();
            Double[] vectorEntrada=descriptoresEntrada.ToArray();
            vectorEntrada = Normalizar(vectorEntrada);
            Double[][] matriz = csvtoMatrix("descriptoresNormalizados");

            int[] pertenencia=new int[matriz.Length];
            for(int i=0;i<pertenencia.Length;i++){
                pertenencia[i]=1;
            }
            pertenencia[23] = 2;

            KNearestNeighbors knn = new KNearestNeighbors(k: 10, inputs: matriz, outputs: pertenencia);
            int answer = knn.Compute(vectorEntrada);
            int[] a = new int[1]; a[0] = 1;
            Double[][] cercanos = knn.GetNearestNeighbors(vectorEntrada,out a);

            List<String> listaSimilares = new List<String>();
            List<canciones> dbcanciones = db.canciones.ToList();
            for (int i = 0; i < matriz.Length; i++)
            {
                if (cercanos.Contains(matriz[i]))
                {
                    listaSimilares.Add(dbcanciones[i].id_spotify.Substring(14));
                }
            }

                //string select="select * from canciones where energy={0} and liveness={1} and tempo={2} and speechiness={3} and acousticness={4} and loudness={5} and valence={6} and danceability={7} and instrumentalness={8} and key={9}";
                //string select2 = "select * from canciones";
                //for(int j=0;j<cercanos.Length;j++){
                //    object[] parameters = new object[10];
                //    for (int i = 0; i < 10; i++)
                //    {
                //            SqlParameter param = new SqlParameter("i", cercanos[j][i]);
                //            parameters[i] = cercanos[j][i];
                //        }
                //        var stores = db.Database.SqlQuery<canciones>(select, parameters).ToList();
                //        listaSimilares.Add(stores[0].id_spotify);
                //}

                return listaSimilares;
        }
 private Double[][] getCancionesDB()
 {
     ModeloSimilitudEntities db = new ModeloSimilitudEntities();
     List<canciones> musicas = db.canciones.ToList();
     int tamano = musicas.Count;
     Double[][] listaCanciones = new Double[tamano][];
     for (int i = 0; i < musicas.Count; i++)
     {
         canciones cancion = musicas[i];
         listaCanciones[i] = new Double[] { cancion.energy, cancion.liveness, cancion.tempo, cancion.speechiness, cancion.acousticness, cancion.loudness, cancion.valence, cancion.danceability, cancion.instrumentalness, Double.Parse(cancion.key.ToString()) };
     }
     return listaCanciones;
 }
        private List<String> GetSimilaresDatabaseKmeans(List<Double> descriptoresEntrada)
        {
            ModeloSimilitudEntities db = new ModeloSimilitudEntities();
            List<canciones> ListaCanciones = db.canciones.ToList();
            Double[] vectorEntrada = descriptoresEntrada.ToArray();
            vectorEntrada = Normalizar(vectorEntrada);
            Double[][] matriz = csvtoMatrix("descriptoresNormalizados");
            int Nclusters = 7;
            KMeans kmeans = new KMeans(Nclusters, Accord.Math.Distance.Chebyshev);
            int[] indices = kmeans.Compute(matriz);
            int Cluster =kmeans.Nearest(vectorEntrada);

            int nroSimilares = 10;
            int[] indiceSimilar=new int[nroSimilares];

            for(int j=0;j<nroSimilares;j++){
                Double distancia = 1000;
                for (int i = 0; i < indices.Length; i++)
                {
                    if (!indiceSimilar.Contains(i))
                    {
                        if (Cluster == indices[i])
                        {
                            Double distanciatemp = Accord.Math.Distance.Chebyshev(vectorEntrada, matriz[i]);
                            if (distanciatemp < distancia)
                            {
                                distancia = distanciatemp;
                                indiceSimilar[j] = i;
                            }
                        }
                    }
                }
            }

            List<String> listaSimilares = new List<String>();
            foreach (int i in indiceSimilar)
            {
                listaSimilares.Add(ListaCanciones[i].id_spotify.Substring(14));
            }

            //string select="select * from canciones where energy={0} and liveness={1} and tempo={2} and speechiness={3} and acousticness={4} and loudness={5} and valence={6} and danceability={7} and instrumentalness={8} and key={9}";
            //string select2 = "select * from canciones";
            //for(int j=0;j<cercanos.Length;j++){
            //    object[] parameters = new object[10];
            //    for (int i = 0; i < 10; i++)
            //    {
            //            SqlParameter param = new SqlParameter("i", cercanos[j][i]);
            //            parameters[i] = cercanos[j][i];
            //        }
            //        var stores = db.Database.SqlQuery<canciones>(select, parameters).ToList();
            //        listaSimilares.Add(stores[0].id_spotify);
            //}

            return listaSimilares;
        }
        public void getSimilaresLastFM()
        {
            ModeloSimilitudEntities db = new ModeloSimilitudEntities();
            Dictionary<String, String> canciones = getNames();
            foreach (String cancion in canciones.Keys)
            {
                int tiempo = 2000;
                Thread.Sleep(tiempo);
                String artista = canciones[cancion];
                String jsonRequest = "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=" + artista + "&track=" + cancion + "&api_key=7e609960174aab0894676a8cca49548b&format=json";
                try
                {
                    String jsonResultSimilars = SONGGET(jsonRequest);
                    JObject jObject = JObject.Parse(jsonResultSimilars);
                    JToken tokenSimilars = jObject["similartracks"];
                    Array arrayTracks = tokenSimilars["track"].ToArray();
                    for (int i = 0; i < arrayTracks.Length; i++)
                    {
                        similares similar = new similares();
                        JToken tokenAudioSimilar = (JToken)arrayTracks.GetValue(i);
                        similar.Artist_Original = artista;
                        similar.Song_Original = cancion;
                        JToken tokenArtistSimilar = tokenAudioSimilar["artist"];
                        similar.Artist_Similar = tokenArtistSimilar["name"].ToString();
                        similar.Song_Similar = tokenAudioSimilar["name"].ToString();
                        similar.Valor_Similitud = i;
                        db.similares.Add(similar);
                        int numberOfObjects = db.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    System.IO.File.AppendAllText(@"C:\Users\FastSolution\Documents\Visual Studio 2013\Projects\BusquedaSimilitud\Similitud.Web\App_Data\log\noencontrados.txt", cancion + "-" + artista + Environment.NewLine);
                }

            }
        }
 private void ExportarCSVFormat()
 {
     ModeloSimilitudEntities db = new ModeloSimilitudEntities();
     List<canciones> musicas = db.canciones.ToList();
     foreach (canciones cancion in musicas)
     {
         String descriptoresXlinea = cancion.energy.ToString() + "," + cancion.tempo.ToString() + "," + cancion.speechiness.ToString() + "," + cancion.acousticness.ToString() + "," + cancion.loudness.ToString() + "," + cancion.valence.ToString() + "," + cancion.danceability.ToString() + "," + cancion.instrumentalness.ToString() + "," + cancion.key.ToString();
         System.IO.File.AppendAllText(@"C:\Users\FastSolution\Documents\Visual Studio 2013\Projects\BusquedaSimilitud\Similitud.Web\App_Data\Matlab\descriptores.txt", descriptoresXlinea + Environment.NewLine);
     }
 }
        }//desde DB file echo nest
        private void SaveSimilarCanciones()
        {
            ModeloSimilitudEntities db = new ModeloSimilitudEntities();

            List<similares> ListaSimilares = db.similares.ToList();
            string id_song, json, jsonResult;
            for (int i = 11547; i < ListaSimilares.Count; i++)
            {
                ModeloSimilitudEntities database = new ModeloSimilitudEntities();
                similares similar = ListaSimilares[i];
                int milliseconds = 3000;
                Thread.Sleep(milliseconds);
                String artist_similar = similar.Artist_Similar;
                String song_similar = similar.Song_Similar;

                json = "http://developer.echonest.com/api/v4/song/search?api_key=ERYL0FA7VZ24XQMOO&format=json&results=1&artist=" + artist_similar + "&title=" + song_similar + "&bucket=id:spotify&bucket=tracks&limit=true&bucket=audio_summary";
                jsonResult = SONGGET(json);
                if (!jsonResult.Equals(""))
                {
                    string cancionesNoEncontradas = "";
                    canciones cancion = new canciones();
                    try
                    {
                        JObject jObject = JObject.Parse(jsonResult);
                        Array arraySongs = ((jObject["response"])["songs"]).ToArray();
                        JToken tokenSongs = (JToken)(arraySongs.GetValue(0));
                        JToken tokenSummary = tokenSongs["audio_summary"];

                        cancion.energy = Double.Parse(tokenSummary["energy"].ToString());
                        cancion.liveness = Double.Parse(tokenSummary["liveness"].ToString());
                        cancion.tempo = Double.Parse(tokenSummary["tempo"].ToString());
                        cancion.speechiness = Double.Parse(tokenSummary["speechiness"].ToString());
                        cancion.acousticness = Double.Parse(tokenSummary["acousticness"].ToString());
                        cancion.loudness = Double.Parse(tokenSummary["loudness"].ToString());
                        cancion.valence = Double.Parse(tokenSummary["valence"].ToString());
                        cancion.danceability = Double.Parse(tokenSummary["danceability"].ToString());
                        cancion.instrumentalness = Double.Parse(tokenSummary["instrumentalness"].ToString());
                        cancion.key = int.Parse(tokenSummary["key"].ToString());

                        Array arrayTracks = tokenSongs["tracks"].ToArray();
                        JToken tokenTracks = (JToken)arrayTracks.GetValue(0);
                        cancion.id_spotify = tokenTracks["foreign_id"].ToString();

                        cancion.track_id = tokenTracks["id"].ToString();
                        cancion.title = tokenSongs["title"].ToString();
                        cancion.song_id = tokenSongs["id"].ToString();
                        cancion.artist_id = tokenSongs["artist_id"].ToString();
                        cancion.artist_mbid = "";//falta
                        cancion.artist_name = tokenSongs["artist_name"].ToString();
                        cancion.duration = Double.Parse(tokenSummary["duration"].ToString());
                        cancion.artist_familiarity = 0;//falta
                        cancion.artist_hotttnesss = 0;//falta
                        cancion.year = 0;//falta
                        database.canciones.Add(cancion);
                        int numberOfObjects = database.SaveChanges();
                    }
                    catch (Exception e)
                    {

                        System.IO.File.AppendAllText(@"C:\Users\FastSolution\Documents\Visual Studio 2013\Projects\BusquedaSimilitud\Similitud.Web\App_Data\log\noencontradosEchoNest.txt", similar.Song_Similar + "-" + similar.Artist_Similar + i + Environment.NewLine);
                    }
                }

            }
        }
        private void CargadoCanciones()
        {
            ModeloSimilitudEntities db = new ModeloSimilitudEntities();
            subset_track_metadataEntities sm = new subset_track_metadataEntities();

            List<songs> musicas = sm.songs.ToList();
            string id_song, json, jsonResult;
            for (int i = 7212; i <= musicas.Count; i++)
            {
                songs song = musicas[i];
                int milliseconds = 3000;
                Thread.Sleep(milliseconds);
                id_song = song.song_id;
                json = "http://developer.echonest.com/api/v4/song/profile?api_key=ERYL0FA7VZ24XQMOO&format=json&results=1&id=" + id_song + "&bucket=id:spotify&bucket=tracks&limit=true&bucket=audio_summary";
                jsonResult = SONGGET(json);
                if (!jsonResult.Equals(""))
                {
                    string cancionesNoEncontradas = "";
                    canciones cancion = new canciones();
                    try
                    {
                        JObject jObject = JObject.Parse(jsonResult);
                        Array arraySongs = ((jObject["response"])["songs"]).ToArray();
                        JToken tokenSongs = (JToken)(arraySongs.GetValue(0));
                        JToken tokenSummary = tokenSongs["audio_summary"];

                        cancion.energy = Double.Parse(tokenSummary["energy"].ToString());
                        cancion.liveness = Double.Parse(tokenSummary["liveness"].ToString());
                        cancion.tempo = Double.Parse(tokenSummary["tempo"].ToString());
                        cancion.speechiness = Double.Parse(tokenSummary["speechiness"].ToString());
                        cancion.acousticness = Double.Parse(tokenSummary["acousticness"].ToString());
                        cancion.loudness = Double.Parse(tokenSummary["loudness"].ToString());
                        cancion.valence = Double.Parse(tokenSummary["valence"].ToString());
                        cancion.danceability = Double.Parse(tokenSummary["danceability"].ToString());
                        cancion.instrumentalness = Double.Parse(tokenSummary["instrumentalness"].ToString());
                        cancion.key = int.Parse(tokenSummary["key"].ToString());

                        Array arrayTracks = tokenSongs["tracks"].ToArray();
                        JToken tokenTracks = (JToken)arrayTracks.GetValue(0);
                        cancion.id_spotify = tokenTracks["foreign_id"].ToString();

                        cancion.track_id = song.track_id;
                        cancion.title = song.title;
                        cancion.song_id = song.song_id;
                        cancion.artist_id = song.artist_id;
                        cancion.artist_mbid = song.artist_mbid;
                        cancion.artist_name = song.artist_name;
                        cancion.duration = Double.Parse(song.duration.ToString());
                        cancion.artist_familiarity = song.artist_familiarity;
                        cancion.artist_hotttnesss = song.artist_hotttnesss;
                        cancion.year = int.Parse(song.year.ToString());
                        db.canciones.Add(cancion);
                        int numberOfObjects = db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        System.IO.File.AppendAllText(@"C:\Users\FastSolution\Documents\Visual Studio 2013\Projects\BusquedaSimilitud\Similitud.Web\App_Data\log\registros.txt", song.song_id + "\n");
                    }
                }

            }
        }//desde DB file echo nest