Esempio n. 1
0
        private AnnoList ConvertDiscreteAnnoListToContinuousList(AnnoList annolist, double chunksize, double end, string restclass = "Rest")
        {
            AnnoList result = new AnnoList();

            result.Scheme = annolist.Scheme;
            result.Meta   = annolist.Meta;
            double currentpos = 0;

            bool foundlabel = false;

            while (currentpos < end)
            {
                foundlabel = false;
                foreach (AnnoListItem orgitem in annolist)
                {
                    if (orgitem.Start * 1000 < currentpos && orgitem.Stop * 1000 > currentpos)
                    {
                        AnnoListItem ali = new AnnoListItem(currentpos, chunksize, orgitem.Label);
                        result.Add(ali);
                        foundlabel = true;
                        break;
                    }
                }

                if (foundlabel == false)
                {
                    AnnoListItem ali = new AnnoListItem(currentpos, chunksize, restclass);
                    result.Add(ali);
                }

                currentpos = currentpos + chunksize;
            }

            return(result);
        }
Esempio n. 2
0
        private AnnoList ResampleContinuousList(AnnoList annolist, double targetsr)
        {
            double sr = annolist.Scheme.SampleRate;

            if (sr == targetsr)
            {
                return(annolist);
            }

            AnnoList result = new AnnoList();

            result.Scheme = annolist.Scheme;
            result.Meta   = annolist.Meta;

            //upsample
            if (sr < targetsr)
            {
                double factor = targetsr / sr;
                double round  = Math.Round(factor);

                if (factor - round == 0)
                {
                    for (int i = 0; i < annolist.Count; i++)
                    {
                        for (int j = 0; j < round; j++)
                        {
                            AnnoListItem ali = new AnnoListItem(annolist[i].Start + j * (1.0 / round), (1.0 / round), annolist[i].Score);

                            result.Add(ali);
                        }
                    }
                }
                else
                {
                    return(null);
                }
            }

            //downsample
            else if (sr > targetsr)
            {
                double factor = sr / targetsr;
                double round  = Math.Round(factor);
                for (int i = 0; i < annolist.Count; i = i + (int)round)
                {
                    result.Add(annolist[i]);
                }
            }

            return(result);
        }
Esempio n. 3
0
        public static AnnoList ConvertFreetoDiscreteAnnotation(AnnoList list)
        {
            if (list.Scheme.Type != AnnoScheme.TYPE.FREE)
            {
                return(list);
            }


            AnnoList   al     = new AnnoList();
            AnnoScheme scheme = new AnnoScheme();

            scheme.Type = AnnoScheme.TYPE.DISCRETE;

            foreach (AnnoListItem ali in list)
            {
                al.Add(ali);
                if (scheme.Labels.Find(x => x.Name == ali.Label) == null)
                {
                    AnnoScheme.Label l = new AnnoScheme.Label(ali.Label, Colors.Black);
                    scheme.Labels.Add(l);
                }
            }

            scheme.Name = list.Scheme.Name;
            al.Scheme   = scheme;
            al.Meta     = list.Meta;

            return(al);
        }
Esempio n. 4
0
        public AnnoList ExportToAnno()
        {
            AnnoList annoList = new AnnoList();

            annoList.Scheme            = new AnnoScheme();
            annoList.Scheme.Type       = AnnoScheme.TYPE.CONTINUOUS;
            annoList.Scheme.MinScore   = min[ShowDim];
            annoList.Scheme.MaxScore   = max[ShowDim];
            annoList.Scheme.SampleRate = rate;

            AnnoListItem annoListItem;
            double       dur = 1 / rate;

            for (int i = 0; i < number; i++)
            {
                annoListItem = new AnnoListItem(i * dur, dur, data[i * dim + ShowDim].ToString(), "", annoList.Scheme.MaxOrForeColor);
                annoList.Add(annoListItem);
                annoList.Scheme.Name = Name;
            }

            return(annoList);
        }
Esempio n. 5
0
        public static AnnoList LoadfromFile(string filepath)
        {
            AnnoList list = new AnnoList();

            list.Source.File.Path = filepath;
            list.Scheme           = new AnnoScheme();
            list.Scheme.Labels    = new List <AnnoScheme.Label>();

            //try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filepath);

                XmlNode annotation = doc.SelectSingleNode("annotation");

                XmlNode info = annotation.SelectSingleNode("info");
                list.Source.File.Type = info.Attributes["ftype"].Value == AnnoSource.FileSource.TYPE.ASCII.ToString() ? AnnoSource.FileSource.TYPE.ASCII : AnnoSource.FileSource.TYPE.BINARY;
                int size = int.Parse(info.Attributes["size"].Value);

                XmlNode meta = annotation.SelectSingleNode("meta");
                if (meta != null)
                {
                    if (meta.Attributes["role"] != null)
                    {
                        list.Meta.Role = meta.Attributes["role"].Value;
                    }
                    if (meta.Attributes["annotator"] != null)
                    {
                        list.Meta.Annotator = meta.Attributes["annotator"].Value;
                    }
                }

                XmlNode scheme = annotation.SelectSingleNode("scheme");
                if (scheme.Attributes["name"] != null)
                {
                    list.Scheme.Name = scheme.Attributes["name"].Value;
                }
                string type = "FREE";
                if (scheme.Attributes["type"] != null)
                {
                    type = scheme.Attributes["type"].Value;
                }

                if (type == AnnoScheme.TYPE.DISCRETE.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.DISCRETE;
                }
                else if (type == AnnoScheme.TYPE.CONTINUOUS.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.CONTINUOUS;
                }
                else if (type == AnnoScheme.TYPE.FREE.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.FREE;
                }

                else if (type == AnnoScheme.TYPE.POINT.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.POINT;
                }
                else if (type == AnnoScheme.TYPE.POLYGON.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.POLYGON;
                }
                else if (type == AnnoScheme.TYPE.GRAPH.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.GRAPH;
                }
                else if (type == AnnoScheme.TYPE.SEGMENTATION.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.SEGMENTATION;
                }

                if (scheme.Attributes["color"] != null)
                {
                    list.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["color"].Value);
                }
                else if (scheme.Attributes["mincolor"] != null)
                {
                    list.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["mincolor"].Value);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.MinOrBackColor = Defaults.Colors.GradientMin;
                }

                if (scheme.Attributes["maxcolor"] != null)
                {
                    list.Scheme.MaxOrForeColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["maxcolor"].Value);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.MaxOrForeColor = Defaults.Colors.GradientMax;
                }

                Dictionary <string, string> LabelIds = new Dictionary <string, string>();

                if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                {
                    foreach (XmlNode item in scheme)
                    {
                        LabelIds.Add(item.Attributes["id"].Value, item.Attributes["name"].Value);

                        Color color = Defaults.Colors.Foreground;
                        if (item.Attributes["color"] != null)
                        {
                            color = (Color)ColorConverter.ConvertFromString(item.Attributes["color"].Value);
                        }
                        AnnoScheme.Label lcp = new AnnoScheme.Label(item.Attributes["name"].Value, color);
                        list.Scheme.Labels.Add(lcp);
                    }

                    AnnoScheme.Label garbage = new AnnoScheme.Label("GARBAGE", Defaults.Colors.Foreground);
                    list.Scheme.Labels.Add(garbage);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                {
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.MinScore   = double.Parse(scheme.Attributes["min"].Value);
                    list.Scheme.MaxScore   = double.Parse(scheme.Attributes["max"].Value);
                    list.Scheme.SampleRate = double.Parse(scheme.Attributes["sr"].Value);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.POINT ||
                         list.Scheme.Type == AnnoScheme.TYPE.POLYGON || list.Scheme.Type == AnnoScheme.TYPE.GRAPH ||
                         list.Scheme.Type == AnnoScheme.TYPE.SEGMENTATION)
                {
                    list.Scheme.SampleRate     = double.Parse(scheme.Attributes["sr"].Value);
                    list.Scheme.NumberOfPoints = int.Parse(scheme.Attributes["num"].Value);
                }

                if (File.Exists(filepath + "~"))

                {
                    if (list.Source.File.Type == AnnoSource.FileSource.TYPE.ASCII)
                    {
                        StreamReader sr    = new StreamReader(filepath + "~", System.Text.Encoding.UTF8);
                        string       line  = null;
                        double       start = 0.0;

                        while ((line = sr.ReadLine()) != null)
                        {
                            string[] data = line.Split(';');
                            if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                            {
                                double value = double.NaN;
                                double.TryParse(data[0], out value);
                                double       confidence = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                AnnoListItem e          = new AnnoListItem(start, 1 / list.Scheme.SampleRate, value, "", Defaults.Colors.Foreground, confidence);
                                list.Add(e);
                                start = start + 1 / list.Scheme.SampleRate;
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                            {
                                start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture);
                                double stop  = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                double dur   = stop - start;
                                string label = "";
                                if (int.Parse(data[2]) < 0)
                                {
                                    label = "GARBAGE";
                                }
                                else
                                {
                                    LabelIds.TryGetValue(data[2], out label);
                                }
                                Color color = Colors.Black;

                                if (list.Scheme.Labels.Find(x => x.Name == label) != null)
                                {
                                    color = list.Scheme.Labels.Find(x => x.Name == label).Color;
                                }

                                double       confidence = Convert.ToDouble(data[3], CultureInfo.InvariantCulture);
                                AnnoListItem e          = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                            {
                                start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture);
                                double stop       = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                double dur        = stop - start;
                                string label      = data[2];
                                double confidence = Convert.ToDouble(data[3], CultureInfo.InvariantCulture);
                                Color  color      = Colors.Black;
                                if (data.Length > 4)
                                {
                                    string[] metapairs = data[4].Split('=');
                                    for (int i = 0; i < metapairs.Length; i++)
                                    {
                                        if (metapairs[i].Contains("color"))
                                        {
                                            color = (Color)ColorConverter.ConvertFromString(metapairs[i + 1]);
                                            break;
                                        }
                                    }
                                }
                                AnnoListItem e = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }

                            else if (list.Scheme.Type == AnnoScheme.TYPE.POINT)
                            {
                                string    frameLabel      = data[0];
                                double    frameConfidence = Convert.ToDouble(data[data.Count() - 1], CultureInfo.InvariantCulture);
                                PointList points          = new PointList();
                                for (int i = 1; i < data.Count() - 1; ++i)
                                {
                                    string pd = data[i].Replace("(", "");
                                    pd = pd.Replace(")", "");
                                    string[] pointData = pd.Split(':');
                                    points.Add(new PointListItem(double.Parse(pointData[1]), double.Parse(pointData[2]), pointData[0], double.Parse(pointData[3])));
                                }
                                AnnoListItem ali = new AnnoListItem(start, 1 / list.Scheme.SampleRate, frameLabel, "", list.Scheme.MinOrBackColor, frameConfidence, true, points);
                                list.Add(ali);
                                start = start + 1 / list.Scheme.SampleRate;
                            }
                        }
                        sr.Close();
                    }
                    else if (list.Source.File.Type == AnnoSource.FileSource.TYPE.BINARY)
                    {
                        BinaryReader binaryReader = new BinaryReader(File.Open(filepath + "~", FileMode.Open));
                        long         length       = (binaryReader.BaseStream.Length);

                        double start = 0.0;
                        while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
                        {
                            if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                            {
                                double       value      = (double)binaryReader.ReadSingle();
                                double       confidence = (double)binaryReader.ReadSingle();
                                AnnoListItem e          = new AnnoListItem(start, 1 / list.Scheme.SampleRate, value, "", Defaults.Colors.Foreground, confidence);
                                list.Add(e);
                                start = start + 1 / list.Scheme.SampleRate;
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                            {
                                start = binaryReader.ReadDouble();
                                double stop  = binaryReader.ReadDouble();
                                double dur   = stop - start;
                                string label = "";
                                int    index = binaryReader.ReadInt32();
                                if (index < 0)
                                {
                                    label = "GARBAGE";
                                }
                                else
                                {
                                    LabelIds.TryGetValue(index.ToString(), out label);
                                }
                                Color color = Colors.Black;

                                if (list.Scheme.Labels.Find(x => x.Name == label) != null)
                                {
                                    color = list.Scheme.Labels.Find(x => x.Name == label).Color;
                                }
                                double       confidence = Math.Round(binaryReader.ReadSingle(), 3, MidpointRounding.AwayFromZero);
                                AnnoListItem e          = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                            {
                                start = binaryReader.ReadDouble();
                                double       stop         = binaryReader.ReadDouble();
                                double       dur          = stop - start;
                                int          stringlength = (int)binaryReader.ReadUInt32();
                                byte[]       labelasbytes = (binaryReader.ReadBytes(stringlength));
                                string       label        = System.Text.Encoding.Default.GetString(labelasbytes);
                                Color        color        = Colors.Black;
                                double       confidence   = Math.Round(binaryReader.ReadSingle(), 3, MidpointRounding.AwayFromZero);
                                AnnoListItem e            = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                        }

                        binaryReader.Close();
                    }
                }


                //Plugin logic should be called after parsing
                if (meta != null && meta.Attributes["trigger"] != null)
                {
                    string[] triggers = meta.Attributes["trigger"].Value.Split(';');
                    foreach (string trigger in triggers)
                    {
                        try
                        {
                            Match match = Regex.Match(trigger, @"([^{]+)\{([^}]*)\}");
                            if (match.Success && match.Groups.Count == 3)
                            {
                                string dllName   = match.Groups[1].Value;
                                string arguments = match.Groups[2].Value;
                                Dictionary <string, object> args = arguments.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                                   .Select(part => part.Split('='))
                                                                   .ToDictionary(split => split[0], split => (object)split[1]);
                                PluginCaller pluginCaller = new PluginCaller(dllName + ".dll", dllName);
                                AnnoTrigger  annoTrigger  = new AnnoTrigger(list, pluginCaller, args);
                                list.Meta.Trigger.Add(annoTrigger);
                            }
                            else
                            {
                                MessageTools.Warning("could not parse trigger '" + trigger + "'");
                            }
                        }
                        catch (Exception)
                        {
                            MessageTools.Warning("could not parse trigger '" + trigger + "'");
                        }
                    }
                }

                if (meta != null && meta.Attributes["pipeline"] != null)
                {
                    string[] pipelines = meta.Attributes["pipeline"].Value.Split(';');
                    foreach (string pipeline in pipelines)
                    {
                        try
                        {
                            Pipeline pipe = new Pipeline(list, pipeline);
                            list.Meta.Pipeline.Add(pipe);
                        }
                        catch (Exception)
                        {
                            MessageTools.Warning("could not parse pipeline '" + pipeline + "'");
                        }
                    }
                }
            }
            //catch(Exception e)
            //{
            //    MessageBox.Show("An exception occured while reading annotation from '" + filepath + "'");
            //}

            return(list);
        }
Esempio n. 6
0
        public static AnnoList LoadfromFile(string filepath)
        {
            AnnoList list = new AnnoList();

            list.Source.File.Path = filepath;
            list.Scheme           = new AnnoScheme();
            list.Scheme.Labels    = new List <AnnoScheme.Label>();

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filepath);

                XmlNode annotation = doc.SelectSingleNode("annotation");

                XmlNode info = annotation.SelectSingleNode("info");
                list.Source.File.Type = info.Attributes["ftype"].Value == AnnoSource.FileSource.TYPE.ASCII.ToString() ? AnnoSource.FileSource.TYPE.ASCII : AnnoSource.FileSource.TYPE.BINARY;
                int size = int.Parse(info.Attributes["size"].Value);

                XmlNode meta = annotation.SelectSingleNode("meta");
                if (meta != null)
                {
                    if (meta.Attributes["role"] != null)
                    {
                        list.Meta.Role = meta.Attributes["role"].Value;
                    }
                    if (meta.Attributes["annotator"] != null)
                    {
                        list.Meta.Annotator = meta.Attributes["annotator"].Value;
                    }
                }

                XmlNode scheme = annotation.SelectSingleNode("scheme");
                if (scheme.Attributes["name"] != null)
                {
                    list.Scheme.Name = scheme.Attributes["name"].Value;
                }
                string type = "FREE";
                if (scheme.Attributes["type"] != null)
                {
                    type = scheme.Attributes["type"].Value;
                }

                if (type == AnnoScheme.TYPE.DISCRETE.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.DISCRETE;
                }
                else if (type == AnnoScheme.TYPE.CONTINUOUS.ToString())
                {
                    list.Scheme.Type = AnnoScheme.TYPE.CONTINUOUS;
                }
                else
                {
                    list.Scheme.Type = AnnoScheme.TYPE.FREE;
                }

                if (scheme.Attributes["color"] != null)
                {
                    list.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["color"].Value);
                }
                else if (scheme.Attributes["mincolor"] != null)
                {
                    list.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["mincolor"].Value);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.MinOrBackColor = Colors.Orange;
                }

                if (scheme.Attributes["maxcolor"] != null)
                {
                    list.Scheme.MaxOrForeColor = (Color)ColorConverter.ConvertFromString(scheme.Attributes["maxcolor"].Value);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.MaxOrForeColor = Colors.LightBlue;
                }

                Dictionary <string, string> LabelIds = new Dictionary <string, string>();

                if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                {
                    foreach (XmlNode item in scheme)
                    {
                        LabelIds.Add(item.Attributes["id"].Value, item.Attributes["name"].Value);

                        Color color = Colors.Black;
                        if (item.Attributes["color"] != null)
                        {
                            color = (Color)ColorConverter.ConvertFromString(item.Attributes["color"].Value);
                        }
                        AnnoScheme.Label lcp = new AnnoScheme.Label(item.Attributes["name"].Value, color);
                        list.Scheme.Labels.Add(lcp);
                    }

                    AnnoScheme.Label garbage = new AnnoScheme.Label("GARBAGE", Colors.Black);
                    list.Scheme.Labels.Add(garbage);
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                {
                }
                else if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    list.Scheme.SampleRate = double.Parse(scheme.Attributes["sr"].Value);
                    list.Scheme.MinScore   = double.Parse(scheme.Attributes["min"].Value);
                    list.Scheme.MaxScore   = double.Parse(scheme.Attributes["max"].Value);
                }

                if (File.Exists(filepath + "~"))

                {
                    if (list.Source.File.Type == AnnoSource.FileSource.TYPE.ASCII)
                    {
                        StreamReader sr    = new StreamReader(filepath + "~", System.Text.Encoding.Default);
                        string       line  = null;
                        double       start = 0.0;

                        while ((line = sr.ReadLine()) != null)
                        {
                            string[] data = line.Split(';');
                            if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                            {
                                string       value      = data[0];
                                double       confidence = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                AnnoListItem e          = new AnnoListItem(start, (1000.0 / list.Scheme.SampleRate) / 1000.0, value, "", Colors.Black, confidence);
                                list.Add(e);
                                start = start + (1000.0 / list.Scheme.SampleRate) / 1000.0;
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                            {
                                start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture);
                                double stop  = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                double dur   = stop - start;
                                string label = "";
                                if (int.Parse(data[2]) < 0)
                                {
                                    label = "GARBAGE";
                                }
                                else
                                {
                                    LabelIds.TryGetValue(data[2], out label);
                                }
                                Color color = Colors.Black;

                                if (list.Scheme.Labels.Find(x => x.Name == label) != null)
                                {
                                    color = list.Scheme.Labels.Find(x => x.Name == label).Color;
                                }

                                double       confidence = Convert.ToDouble(data[3], CultureInfo.InvariantCulture);
                                AnnoListItem e          = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                            {
                                start = Convert.ToDouble(data[0], CultureInfo.InvariantCulture);
                                double stop       = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
                                double dur        = stop - start;
                                string label      = data[2];
                                double confidence = Convert.ToDouble(data[3], CultureInfo.InvariantCulture);
                                Color  color      = Colors.Black;
                                if (data.Length > 4)
                                {
                                    string[] metapairs = data[4].Split('=');
                                    for (int i = 0; i < metapairs.Length; i++)
                                    {
                                        if (metapairs[i].Contains("color"))
                                        {
                                            color = (Color)ColorConverter.ConvertFromString(metapairs[i + 1]);
                                            break;
                                        }
                                    }
                                }
                                AnnoListItem e = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                        }
                        sr.Close();
                    }
                    else if (list.Source.File.Type == AnnoSource.FileSource.TYPE.BINARY)
                    {
                        BinaryReader binaryReader = new BinaryReader(File.Open(filepath + "~", FileMode.Open));
                        long         length       = (binaryReader.BaseStream.Length);

                        double start = 0.0;
                        while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
                        {
                            if (list.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                            {
                                string       value      = binaryReader.ReadSingle().ToString();
                                double       confidence = (double)binaryReader.ReadSingle();
                                AnnoListItem e          = new AnnoListItem(start, (1000.0 / list.Scheme.SampleRate) / 1000.0, value, "", Colors.Black, confidence);
                                list.Add(e);
                                start = start + (1000.0 / list.Scheme.SampleRate) / 1000.0;
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                            {
                                start = binaryReader.ReadDouble();
                                double stop  = binaryReader.ReadDouble();
                                double dur   = stop - start;
                                string label = "";
                                int    index = binaryReader.ReadInt32();
                                if (index < 0)
                                {
                                    label = "GARBAGE";
                                }
                                else
                                {
                                    LabelIds.TryGetValue(index.ToString(), out label);
                                }
                                Color color = Colors.Black;

                                if (list.Scheme.Labels.Find(x => x.Name == label) != null)
                                {
                                    color = list.Scheme.Labels.Find(x => x.Name == label).Color;
                                }
                                double       confidence = Math.Round(binaryReader.ReadSingle(), 3, MidpointRounding.AwayFromZero);
                                AnnoListItem e          = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                            else if (list.Scheme.Type == AnnoScheme.TYPE.FREE)
                            {
                                start = binaryReader.ReadDouble();
                                double       stop         = binaryReader.ReadDouble();
                                double       dur          = stop - start;
                                int          stringlength = (int)binaryReader.ReadUInt32();
                                byte[]       labelasbytes = (binaryReader.ReadBytes(stringlength));
                                string       label        = System.Text.Encoding.Default.GetString(labelasbytes);
                                Color        color        = Colors.Black;
                                double       confidence   = Math.Round(binaryReader.ReadSingle(), 3, MidpointRounding.AwayFromZero);
                                AnnoListItem e            = new AnnoListItem(start, dur, label, "", color, confidence);
                                list.AddSorted(e);
                            }
                        }

                        binaryReader.Close();
                    }
                }
                else
                {
                    MessageBox.Show("Annotation data was not found, load scheme only from '" + filepath + "'");
                }
                list.HasChanged = false;
            }
            catch (Exception e)
            {
                MessageBox.Show("An exception occured while reading annotation from '" + filepath + "'");
            }

            return(list);
        }
Esempio n. 7
0
        private void ExportAnnoContinuousToDiscrete()
        {
            if (AnnoTierStatic.Selected != null && !AnnoTierStatic.Selected.IsDiscreteOrFree)
            {
                Dictionary <string, UserInputWindow.Input> input = new Dictionary <string, UserInputWindow.Input>();
                input["labels"] = new UserInputWindow.Input()
                {
                    Label = "Class labels (separated by ;)", DefaultValue = Properties.Settings.Default.ConvertToDiscreteClasses
                };
                input["thresholds"] = new UserInputWindow.Input()
                {
                    Label = "Upper thresholds (separated by ;)", DefaultValue = Properties.Settings.Default.ConvertToDiscreteThreshs
                };
                input["offset"] = new UserInputWindow.Input()
                {
                    Label = "Optional offset (s)", DefaultValue = Properties.Settings.Default.ConvertToDiscreteDelays
                };
                UserInputWindow dialog = new UserInputWindow("Convert to discrete annotation", input);
                dialog.ShowDialog();

                List <string> classes         = new List <string>();
                List <double> upperThresholds = new List <double>();
                double        offset          = 0.0;

                if (dialog.DialogResult == true)
                {
                    Properties.Settings.Default.ConvertToDiscreteClasses = dialog.Result("labels");
                    Properties.Settings.Default.ConvertToDiscreteThreshs = dialog.Result("thresholds");
                    Properties.Settings.Default.ConvertToDiscreteDelays  = dialog.Result("offset");
                    Properties.Settings.Default.Save();


                    string[] labels = dialog.Result("labels").Split(';');
                    for (int i = 0; i < labels.Length; i++)
                    {
                        classes.Add(labels[i]);
                    }

                    string[] thresholds = dialog.Result("thresholds").Split(';');
                    for (int i = 0; i < thresholds.Length; i++)
                    {
                        double thresh = -1;
                        double.TryParse(thresholds[i], out thresh);
                        if (thresh > -1)
                        {
                            upperThresholds.Add(thresh);
                        }
                        else
                        {
                            MessageTools.Warning("Could not parse input");
                        }
                    }

                    if (thresholds.Length == labels.Length - 1)
                    {
                        upperThresholds.Add(1.0);
                    }
                    else if (thresholds.Length == labels.Length + 1)
                    {
                        classes.Add("REST");
                    }
                    else if (thresholds.Length != labels.Length)
                    {
                        MessageBox.Show("Number of labels does not match number of threshholds");
                    }

                    double.TryParse(dialog.Result("offset"), out offset);
                }
                Mouse.SetCursor(Cursors.No);

                AnnoList discretevalues = new AnnoList();
                discretevalues.Scheme         = new AnnoScheme();
                discretevalues.Scheme.Type    = AnnoScheme.TYPE.DISCRETE;
                discretevalues.Meta.Role      = AnnoTier.Selected.AnnoList.Meta.Role;
                discretevalues.Meta.Annotator = AnnoTier.Selected.AnnoList.Meta.Annotator;
                discretevalues.Scheme.Name    = AnnoTier.Selected.AnnoList.Scheme.Name;

                foreach (string label in classes)
                {
                    AnnoScheme.Label item = new AnnoScheme.Label(label, System.Windows.Media.Colors.Black);
                    discretevalues.Scheme.Labels.Add(item);
                }

                AnnoScheme.Label garbage = new AnnoScheme.Label("GARBAGE", Colors.Black);
                discretevalues.Scheme.Labels.Add(garbage);

                double lowThres  = -Double.MaxValue;
                double highThres = 1.0;

                foreach (AnnoListItem ali in AnnoTierStatic.Selected.AnnoList)
                {
                    double val = ali.Score;

                    for (int i = 0; i < classes.Count; i++)
                    {
                        highThres = upperThresholds[i];
                        if (i > 0)
                        {
                            lowThres = upperThresholds[i - 1];
                        }
                        else
                        {
                            lowThres = -Double.MaxValue;
                        }

                        if (val > lowThres && val <= highThres)
                        {
                            if (!(discretevalues.Count > 0 && discretevalues[discretevalues.Count - 1].Label == classes[i]))
                            {
                                AnnoListItem newItem = new AnnoListItem(ali.Start + offset, ali.Duration, classes[i], "", discretevalues.Scheme.GetColorForLabel(classes[i]));
                                if (newItem.Start < 0.0)
                                {
                                    newItem.Duration = ali.Duration + offset + newItem.Start;
                                    newItem.Start    = 0.0;
                                    newItem.Stop     = newItem.Duration;
                                }
                                if (newItem.Duration > 0.0)
                                {
                                    discretevalues.Add(newItem);
                                }
                            }
                            else
                            {
                                discretevalues[discretevalues.Count - 1].Stop = discretevalues[discretevalues.Count - 1].Stop + ali.Duration;
                            }
                            break;
                        }
                    }
                }

                AnnoTier.Unselect();
                addAnnoTierFromList(discretevalues);

                Mouse.SetCursor(System.Windows.Input.Cursors.Arrow);
            }
            else
            {
                MessageBox.Show("Tier is already discrete");
            }
        }
Esempio n. 8
0
        public static List <AnnoList> LoadFromDatabase(System.Collections.IList collections, string databaseName, string sessionName, string userName)
        {
            MongoClient    mongo    = new MongoClient(ServerConnectionString);
            IMongoDatabase database = mongo.GetDatabase(databaseName);

            var collection  = database.GetCollection <BsonDocument>(DatabaseDefinitionCollections.Annotations);
            var roles       = database.GetCollection <BsonDocument>(DatabaseDefinitionCollections.Roles);
            var annoSchemes = database.GetCollection <BsonDocument>(DatabaseDefinitionCollections.Schemes);

            List <AnnoList> annoLists = new List <AnnoList>();

            foreach (DatabaseAnno anno in collections)
            {
                BsonElement value;
                AnnoList    annoList = new AnnoList();

                ObjectId roleid = GetObjectID(database, DatabaseDefinitionCollections.Roles, "name", anno.Role);
                string   roledb = FetchDBRef(database, DatabaseDefinitionCollections.Roles, "name", roleid);

                ObjectId annoSchemeId = GetObjectID(database, DatabaseDefinitionCollections.Schemes, "name", anno.AnnoScheme);
                string   annotdb      = FetchDBRef(database, DatabaseDefinitionCollections.Schemes, "name", annoSchemeId);

                ObjectId annotatorId = GetObjectID(database, DatabaseDefinitionCollections.Annotators, "fullname", anno.AnnotatorFullname);
                string   annotatdb   = FetchDBRef(database, DatabaseDefinitionCollections.Annotators, "name", annotatorId);
                string   annotatdbfn = FetchDBRef(database, DatabaseDefinitionCollections.Annotators, "fullname", annotatorId);
                annoList.Meta.Annotator         = annotatdb;
                annoList.Meta.AnnotatorFullName = annotatdbfn;

                ObjectId sessionid = GetObjectID(database, DatabaseDefinitionCollections.Sessions, "name", sessionName);
                string   sessiondb = FetchDBRef(database, DatabaseDefinitionCollections.Sessions, "name", sessionid);

                var builder = Builders <BsonDocument> .Filter;

                var filterscheme = builder.Eq("_id", annoSchemeId);
                var result       = collection.Find(filterscheme);
                var annosch      = annoSchemes.Find(filterscheme).Single();

                var filter    = builder.Eq("role_id", roleid) & builder.Eq("scheme_id", annoSchemeId) & builder.Eq("annotator_id", annotatorId) & builder.Eq("session_id", sessionid);
                var documents = collection.Find(filter).ToList();

                annoList.Scheme = new AnnoScheme();
                if (annosch.TryGetElement("type", out value) && annosch["type"].ToString() == AnnoScheme.TYPE.DISCRETE.ToString())
                {
                    annoList.Scheme.Type = AnnoScheme.TYPE.DISCRETE;
                }
                else if (annosch.TryGetElement("type", out value) && annosch["type"].ToString() == AnnoScheme.TYPE.FREE.ToString())
                {
                    annoList.Scheme.Type = AnnoScheme.TYPE.FREE;
                }
                else if (annosch.TryGetElement("type", out value) && annosch["type"].ToString() == AnnoScheme.TYPE.CONTINUOUS.ToString())
                {
                    annoList.Scheme.Type = AnnoScheme.TYPE.CONTINUOUS;
                }

                annoList.Meta.Role   = roledb;
                annoList.Scheme.Name = annosch["name"].ToString();
                var labels = documents[0]["labels"].AsBsonArray;
                if (annoList.Scheme.Type == AnnoScheme.TYPE.CONTINUOUS)
                {
                    if (annosch.TryGetElement("min", out value))
                    {
                        annoList.Scheme.MinScore = double.Parse(annosch["min"].ToString());
                    }
                    if (annosch.TryGetElement("max", out value))
                    {
                        annoList.Scheme.MaxScore = double.Parse(annosch["max"].ToString());
                    }
                    if (annosch.TryGetElement("sr", out value))
                    {
                        annoList.Scheme.SampleRate = double.Parse(annosch["sr"].ToString());
                    }

                    if (annosch.TryGetElement("min_color", out value))
                    {
                        annoList.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(annosch["min_color"].ToString());
                    }
                    if (annosch.TryGetElement("max_color", out value))
                    {
                        annoList.Scheme.MaxOrForeColor = (Color)ColorConverter.ConvertFromString(annosch["max_color"].ToString());
                    }

                    annoList.Scheme.MinScore   = annoList.Scheme.MinScore;
                    annoList.Scheme.MaxScore   = annoList.Scheme.MaxScore;
                    annoList.Scheme.SampleRate = annoList.Scheme.SampleRate;

                    for (int i = 0; i < labels.Count; i++)
                    {
                        string label      = labels[i]["score"].ToString();
                        string confidence = labels[i]["conf"].ToString();
                        double start      = i * ((1000.0 / annoList.Scheme.SampleRate) / 1000.0);
                        double dur        = (1000.0 / annoList.Scheme.SampleRate) / 1000.0;

                        AnnoListItem ali = new AnnoListItem(start, dur, label, "", Colors.Black, double.Parse(confidence));

                        annoList.Add(ali);
                    }
                }
                else if (annoList.Scheme.Type == AnnoScheme.TYPE.DISCRETE)
                {
                    annoList.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(annosch["color"].ToString());

                    annoList.Scheme.Labels = new List <AnnoScheme.Label>();

                    BsonArray schemelabels = annosch["labels"].AsBsonArray;

                    for (int j = 0; j < schemelabels.Count; j++)
                    {
                        //in case flag is set, if not ignore isValid
                        try
                        {
                            if (schemelabels[j]["isValid"].AsBoolean == true)
                            {
                                annoList.Scheme.Labels.Add(new AnnoScheme.Label(schemelabels[j]["name"].ToString(), (Color)ColorConverter.ConvertFromString(schemelabels[j]["color"].ToString())));
                            }
                        }
                        catch
                        {
                            annoList.Scheme.Labels.Add(new AnnoScheme.Label(schemelabels[j]["name"].ToString(), (Color)ColorConverter.ConvertFromString(schemelabels[j]["color"].ToString())));
                        }
                    }

                    annoList.Scheme.Labels.Add(new AnnoScheme.Label(GARBAGELABEL, GARBAGECOLOR));

                    for (int i = 0; i < labels.Count; i++)
                    {
                        string SchemeLabel = "";
                        Color  SchemeColor = Colors.Black;
                        bool   idfound     = false;
                        for (int j = 0; j < schemelabels.Count; j++)
                        {
                            if (labels[i]["id"].AsInt32 == schemelabels[j]["id"].AsInt32)
                            {
                                SchemeLabel = schemelabels[j]["name"].ToString();
                                SchemeColor = (Color)ColorConverter.ConvertFromString(schemelabels[j]["color"].ToString());
                                idfound     = true;
                                break;
                            }
                        }


                        if (labels[i]["id"].AsInt32 == -1 || idfound == false)
                        {
                            SchemeLabel = GARBAGELABEL;
                            SchemeColor = GARBAGECOLOR;
                        }

                        double start      = double.Parse(labels[i]["from"].ToString());
                        double stop       = double.Parse(labels[i]["to"].ToString());
                        double duration   = stop - start;
                        string label      = SchemeLabel;
                        string confidence = labels[i]["conf"].ToString();

                        AnnoListItem ali = new AnnoListItem(start, duration, label, "", SchemeColor, double.Parse(confidence));
                        annoList.AddSorted(ali);
                    }
                }
                else if (annoList.Scheme.Type == AnnoScheme.TYPE.FREE)
                {
                    annoList.Scheme.MinOrBackColor = (Color)ColorConverter.ConvertFromString(annosch["color"].ToString());

                    for (int i = 0; i < labels.Count; i++)
                    {
                        double start      = double.Parse(labels[i]["from"].ToString());
                        double stop       = double.Parse(labels[i]["to"].ToString());
                        double duration   = stop - start;
                        string label      = labels[i]["name"].ToString();
                        string confidence = labels[i]["conf"].ToString();

                        AnnoListItem ali = new AnnoListItem(start, duration, label, "", Colors.Black, double.Parse(confidence));
                        annoList.AddSorted(ali);
                    }
                }

                annoList.Source.Database.OID = anno.Id;

                annoLists.Add(annoList);
                annoList = null;
            }

            return(annoLists);
        }