Esempio n. 1
0
        public void ParallelRun(string path, string outputDir, AveragineType type, ChargerType charger)
        {
            string file   = Path.GetFileNameWithoutExtension(path) + ".mzML";
            string output = Path.Combine(outputDir, file);

            MZMLProducer mZMLProducer = new MZMLProducer();
            var          model        = mZMLProducer.Produce(path, progressingCounter.Add, type, (mzMLWriter.ChargerType)charger);

            var serializer = new XmlSerializer(model.GetType());
            var encoding   = Encoding.GetEncoding("ISO-8859-1");
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
            {
                Indent             = true,
                OmitXmlDeclaration = false,
                Encoding           = Encoding.UTF8
            };

            using (FileStream ostrm = new FileStream(output, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(ostrm))
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(writer, xmlWriterSettings))
                    {
                        serializer.Serialize(xmlWriter, model);
                    }
                }
            }
            // update progress
            progress.Add();
        }
Esempio n. 2
0
        // GetChargerType() -> u32
        public static long GetChargerType(ServiceCtx context)
        {
            ChargerType chargerType = ChargerType.ChargerOrDock;

            context.ResponseData.Write((int)chargerType);

            Logger.PrintStub(LogClass.ServicePsm, new { chargerType });

            return(0);
        }
Esempio n. 3
0
        // GetChargerType() -> u32
        public static ResultCode GetChargerType(ServiceCtx context)
        {
            ChargerType chargerType = ChargerType.ChargerOrDock;

            context.ResponseData.Write((int)chargerType);

            Logger.Stub?.PrintStub(LogClass.ServicePsm, new { chargerType });

            return(ResultCode.Success);
        }
Esempio n. 4
0
        public static ChargerBase GetCharger(BatteryBase battery, ChargerType type)
        {
            switch (type)
            {
            case ChargerType.Theard:
                return(new ChargerThread(battery));

            case ChargerType.Task:
                return(new ChargerTask(battery));

            default:
                throw new NotImplementedException($"Not implemented logic for {type.ToString()} in {nameof(ChargerType)}");
            }
        }
Esempio n. 5
0
        public IPowerSource GetPowerSource(ChargerType type, float outputAmperage, float outputVoltage)
        {
            switch (type)
            {
            case ChargerType.UsbCharger:
                return(new UsbCharger(outputAmperage, outputVoltage));

            case ChargerType.WirelessCharger:
                return(new WirelessCharger(outputAmperage, outputVoltage));

            default:
                throw new NotSupportedException();
            }
        }
 private void SelectCharger(object sender, RoutedEventArgs e)
 {
     if (Patterson.IsChecked == true)
     {
         charger = ChargerType.Patterson;
     }
     else if (Fourier.IsChecked == true)
     {
         charger = ChargerType.Fourier;
     }
     else if (Combined.IsChecked == true)
     {
         charger = ChargerType.Combined;
     }
 }
Esempio n. 7
0
        public void ParallelRun(string path, string outputDir, AveragineType type, ChargerType chargerType)
        {
            string file   = Path.GetFileNameWithoutExtension(path) + ".mgf";
            string output = Path.Combine(outputDir, file);

            ThermoRawSpectrumReader reader  = new ThermoRawSpectrumReader();
            LocalMaximaPicking      picking = new LocalMaximaPicking(ms1PrcisionPPM);

            reader.Init(path);

            Dictionary <int, List <int> > scanGroup = new Dictionary <int, List <int> >();
            int current = -1;
            int start   = reader.GetFirstScan();
            int end     = reader.GetLastScan();

            for (int i = start; i < end; i++)
            {
                if (reader.GetMSnOrder(i) == 1)
                {
                    current      = i;
                    scanGroup[i] = new List <int>();
                }
                else if (reader.GetMSnOrder(i) == 2)
                {
                    scanGroup[current].Add(i);
                }
            }

            List <MS2Info> ms2Infos = new List <MS2Info>();

            Parallel.ForEach(scanGroup, (scanPair) =>
            {
                if (scanPair.Value.Count > 0)
                {
                    ISpectrum ms1 = reader.GetSpectrum(scanPair.Key);
                    foreach (int i in scanPair.Value)
                    {
                        double mz             = reader.GetPrecursorMass(i, reader.GetMSnOrder(i));
                        List <IPeak> ms1Peaks = FilterPeaks(ms1.GetPeaks(), mz, searchRange);

                        if (ms1Peaks.Count() == 0)
                        {
                            continue;
                        }

                        // insert pseudo peaks for large gap
                        List <IPeak> peaks = new List <IPeak>();
                        double precision   = 0.02;
                        double last        = ms1Peaks.First().GetMZ();
                        foreach (IPeak peak in ms1Peaks)
                        {
                            if (peak.GetMZ() - last > precision)
                            {
                                peaks.Add(new GeneralPeak(last + precision / 2, 0));
                                peaks.Add(new GeneralPeak(peak.GetMZ() - precision / 2, 0));
                            }
                            peaks.Add(peak);
                            last = peak.GetMZ();
                        }
                        List <IPeak> majorPeaks = picking.Process(peaks);
                        ICharger charger        = new Patterson();
                        if (chargerType == ChargerType.Fourier)
                        {
                            charger = new Fourier();
                        }
                        else if (chargerType == ChargerType.Combined)
                        {
                            charger = new PattersonFourierCombine();
                        }
                        int charge = charger.Charge(peaks, mz - searchRange, mz + searchRange);

                        // find evelope cluster
                        EnvelopeProcess envelope = new EnvelopeProcess();
                        var cluster = envelope.Cluster(majorPeaks, mz, charge);
                        if (cluster.Count == 0)
                        {
                            continue;
                        }

                        // find monopeak
                        Averagine averagine           = new Averagine(type);
                        BrainCSharp braincs           = new BrainCSharp();
                        MonoisotopicSearcher searcher = new MonoisotopicSearcher(averagine, braincs);
                        MonoisotopicScore result      = searcher.Search(mz, charge, cluster);
                        double precursorMZ            = result.GetMZ();

                        // write mgf
                        ISpectrum ms2      = reader.GetSpectrum(i);
                        IProcess processer = new WeightedAveraging(new LocalNeighborPicking());
                        ms2 = processer.Process(ms2);

                        MS2Info ms2Info = new MS2Info
                        {
                            PrecursorMZ     = result.GetMZ(),
                            PrecursorCharge = charge,
                            Scan            = ms2.GetScanNum(),
                            Retention       = ms2.GetRetention(),
                            Peaks           = ms2.GetPeaks()
                        };
                        lock (resultLock)
                        {
                            ms2Infos.Add(ms2Info);
                        }
                    }
                }
                readingProgress.Add(scanGroup.Count);
            });

            ms2Infos = ms2Infos.OrderBy(m => m.Scan).ToList();
            using (FileStream ostrm = new FileStream(output, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(ostrm))
                {
                    foreach (MS2Info ms2 in ms2Infos)
                    {
                        WriteMGF(writer, path + ",SCANS=" + ms2.Scan.ToString() + ",PRECURSOR=" + ms2.PrecursorMZ, ms2.PrecursorMZ, ms2.PrecursorCharge,
                                 ms2.Scan, ms2.Retention * 60, reader.GetActivation(ms2.Scan), ms2.Peaks);
                        writer.Flush();
                    }
                }
            }

            // update progress
            progress.Add();
        }
        public Run Read(string path, AveragineType type, ChargerType charger, string defaultDataProcessingRef,
                        ProgressUpdate updater)
        {
            Run data = new Run();

            // init reader
            ThermoRawSpectrumReader reader  = new ThermoRawSpectrumReader();
            LocalMaximaPicking      picking = new LocalMaximaPicking(ms1PrcisionPPM);
            IProcess process = new WeightedAveraging(new LocalNeighborPicking());

            reader.Init(path);

            data.spectrumList = new SpectrumList();
            Dictionary <int, Spectrum> spectrumMap = new Dictionary <int, Spectrum>();

            int start = reader.GetFirstScan();
            int end   = reader.GetLastScan();
            Dictionary <int, List <int> > scanGroup = new Dictionary <int, List <int> >();
            int current = -1;

            for (int i = start; i < end; i++)
            {
                if (reader.GetMSnOrder(i) == 1)
                {
                    current      = i;
                    scanGroup[i] = new List <int>();
                }
                else if (reader.GetMSnOrder(i) == 2)
                {
                    scanGroup[current].Add(i);
                }
            }

            Parallel.ForEach(scanGroup, (scanPair) => {
                if (scanPair.Value.Count > 0)
                {
                    int parentScan          = scanPair.Key;
                    ISpectrum ms1           = null;
                    List <IPeak> majorPeaks = new List <IPeak>();
                    Spectrum ms1Spectrum    =
                        ThermoRawRunFactoryHelper.GetMS1Spectrum(ref reader, parentScan, ref ms1);
                    if (ms1Spectrum != null)
                    {
                        lock (resultLock)
                        {
                            spectrumMap[parentScan] = ms1Spectrum;
                        }
                    }

                    foreach (int scan in scanPair.Value)
                    {
                        Spectrum ms2Spectrum =
                            ThermoRawRunFactoryHelper.GetMS2Spectrum(ref reader, scan, type, charger, picking, process, ms1);
                        if (ms2Spectrum != null)
                        {
                            lock (resultLock)
                            {
                                spectrumMap[scan] = ms2Spectrum;
                            }
                        }
                    }
                }
                updater(scanGroup.Count);
            });

            List <Spectrum> spectrumList =
                spectrumMap.OrderBy(s => s.Key).Select(s => s.Value).ToList();

            data.spectrumList.spectrum = new Spectrum[spectrumList.Count];
            spectrumList = spectrumList.OrderBy(x => int.Parse(x.id.Substring(5))).ToList();
            for (int i = 0; i < spectrumList.Count; i++)
            {
                int scan = int.Parse(spectrumList[i].id.Substring(5));
                data.spectrumList.spectrum[i]       = spectrumList[i];
                data.spectrumList.spectrum[i].index = (scan - 1).ToString();
                data.spectrumList.spectrum[i].defaultArrayLength = spectrumList[i].defaultArrayLength;
            }
            data.spectrumList.count = spectrumList.Count.ToString();
            data.spectrumList.defaultDataProcessingRef = defaultDataProcessingRef;

            return(data);
        }
Esempio n. 9
0
        public List <API.Common.Model.ChargePoint> Process(CoreReferenceData coreRefData)
        {
            List <ChargePoint> outputList = new List <ChargePoint>();

            string source = InputData;

            JObject o = JObject.Parse(source);

            var dataList = o["locations"].ToArray();

            var submissionStatus  = coreRefData.SubmissionStatusTypes.First(s => s.ID == (int)StandardSubmissionStatusTypes.Imported_UnderReview);//imported and under review
            var operationalStatus = coreRefData.StatusTypes.First(os => os.ID == 50);
            var unknownStatus     = coreRefData.StatusTypes.First(os => os.ID == 0);
            var usageTypePublic   = coreRefData.UsageTypes.First(u => u.ID == 1);
            var usageTypePrivate  = coreRefData.UsageTypes.First(u => u.ID == 2);
            var operatorUnknown   = coreRefData.Operators.First(opUnknown => opUnknown.ID == 1);

            int itemCount = 0;

            foreach (var item in dataList)
            {
                ChargePoint cp = new ChargePoint();
                cp.DataProvider = new DataProvider()
                {
                    ID = this.DataProviderID
                };                                                                 //carstations.com
                cp.DataProvidersReference = item["post_id"].ToString();
                cp.DateLastStatusUpdate   = DateTime.UtcNow;
                cp.AddressInfo            = new AddressInfo();

                //carstations.com have requested we not use the station names from their data, so we use address
                //cp.AddressInfo.Title = item["name"] != null ? item["name"].ToString() : item["address"].ToString();
                cp.AddressInfo.Title           = item["address"] != null ? item["address"].ToString() : item["post_id"].ToString();
                cp.AddressInfo.Title           = cp.AddressInfo.Title.Trim().Replace("&amp;", "&");
                cp.AddressInfo.RelatedURL      = "http://carstations.com/" + cp.DataProvidersReference;
                cp.DateLastStatusUpdate        = DateTime.UtcNow;
                cp.AddressInfo.AddressLine1    = item["address"].ToString().Trim();
                cp.AddressInfo.Town            = item["city"].ToString().Trim();
                cp.AddressInfo.StateOrProvince = item["region"].ToString().Trim();
                cp.AddressInfo.Postcode        = item["postal_code"].ToString().Trim();
                cp.AddressInfo.Latitude        = double.Parse(item["latitude"].ToString().Trim());
                cp.AddressInfo.Longitude       = double.Parse(item["longitude"].ToString().Trim());

                cp.AddressInfo.ContactTelephone1 = item["phone"].ToString();

                if (!String.IsNullOrEmpty(item["country"].ToString()))
                {
                    string country   = item["country"].ToString();
                    int?   countryID = null;

                    var countryVal = coreRefData.Countries.FirstOrDefault(c => c.Title.ToLower() == country.Trim().ToLower());
                    if (countryVal == null)
                    {
                        country = country.ToUpper();
                        //match country
                        if (country == "UNITED STATES" || country == "US" || country == "USA" || country == "U.S." || country == "U.S.A.")
                        {
                            countryID = 2;
                        }

                        if (country == "UK" || country == "GB" || country == "GREAT BRITAIN" || country == "UNITED KINGDOM")
                        {
                            countryID = 1;
                        }
                    }
                    else
                    {
                        countryID = countryVal.ID;
                    }

                    if (countryID == null)
                    {
                        this.Log("Country Not Matched, will require Geolocation:" + item["country"].ToString());
                    }
                    else
                    {
                        cp.AddressInfo.Country = coreRefData.Countries.FirstOrDefault(cy => cy.ID == countryID);
                    }
                }
                else
                {
                    //default to US if no country identified
                    //cp.AddressInfo.Country = cp.AddressInfo.Country = coreRefData.Countries.FirstOrDefault(cy => cy.ID == 2);
                }

                //System.Diagnostics.Debug.WriteLine(item.ToString());
                string publicCount  = item["public"].ToString();
                string privateCount = item["private"].ToString();

                if (!String.IsNullOrEmpty(publicCount) && publicCount != "0")
                {
                    try
                    {
                        cp.NumberOfPoints = int.Parse(publicCount);
                    }
                    catch (Exception) { }
                    cp.UsageType = usageTypePublic;
                }
                else
                {
                    if (!String.IsNullOrEmpty(privateCount) && privateCount != "0")
                    {
                        try
                        {
                            cp.NumberOfPoints = int.Parse(privateCount);
                        }
                        catch (Exception) { }
                        cp.UsageType = usageTypePrivate;
                    }
                }

                string verifiedFlag = item["verified_flag"].ToString();

                if (!string.IsNullOrEmpty(verifiedFlag) && verifiedFlag != "0")
                {
                    cp.StatusType = operationalStatus;
                }
                else
                {
                    cp.StatusType = unknownStatus;
                }

                //TODO: allow for multiple operators?
                var operatorsNames = item["brands"].ToArray();

                if (operatorsNames.Count() > 0)
                {
                    var operatorName = operatorsNames[0].ToString();
                    var opDetails    = coreRefData.Operators.FirstOrDefault(op => op.Title.ToLower().Contains(operatorName.ToString().ToLower()));
                    if (opDetails != null)
                    {
                        cp.OperatorInfo = opDetails;
                    }
                    else
                    {
                        Log("Operator not matched:" + operatorName);
                    }
                }
                else
                {
                    cp.OperatorInfo = operatorUnknown;
                }

                var connectorTypes = item["techs"].ToArray();
                foreach (var conn in connectorTypes)
                {
                    ConnectionInfo cinfo = new ConnectionInfo()
                    {
                    };
                    ConnectionType cType = new ConnectionType {
                        ID = 0
                    };
                    ChargerType level = null;
                    cinfo.Reference = conn.ToString();

                    if (conn.ToString().ToUpper() == "J1772")
                    {
                        cType    = new ConnectionType();
                        cType.ID = 1; //J1772
                        level    = new ChargerType {
                            ID = 2
                        };                                 //default to level 2
                    }

                    if (conn.ToString().ToUpper() == "CHADEMO")
                    {
                        cType    = new ConnectionType();
                        cType.ID = 2; //CHadeMO
                        level    = new ChargerType {
                            ID = 3
                        };                                 //default to level 3
                    }
                    if (conn.ToString().ToUpper() == "NEMA5")
                    {
                        cType    = new ConnectionType();
                        cType.ID = 9; //NEMA5-20R
                        level    = new ChargerType {
                            ID = 1
                        };                                 //default to level 1
                    }

                    if (cType.ID == 0)
                    {
                        var conType = coreRefData.ConnectionTypes.FirstOrDefault(ct => ct.Title.ToLower().Contains(conn.ToString().ToLower()));
                        if (conType != null)
                        {
                            cType = conType;
                        }
                    }
                    cinfo.ConnectionType = cType;
                    cinfo.Level          = level;

                    if (cp.Connections == null)
                    {
                        cp.Connections = new List <ConnectionInfo>();
                        if (!IsConnectionInfoBlank(cinfo))
                        {
                            cp.Connections.Add(cinfo);
                        }
                    }
                }

                if (cp.DataQualityLevel == null)
                {
                    cp.DataQualityLevel = 2;
                }

                cp.SubmissionStatus = submissionStatus;

                if (IsPOIValidForImport(cp))
                {
                    outputList.Add(cp);
                }

                itemCount++;
            }

            return(outputList);
        }
Esempio n. 10
0
        public List <API.Common.Model.ChargePoint> Process(CoreReferenceData coreRefData)
        {
            List <ChargePoint> outputList = new List <ChargePoint>();

            string source = InputData;

            JObject o = JObject.Parse(source);

            var dataList = o["ChargeDevice"].ToArray();

            var submissionStatus                  = coreRefData.SubmissionStatusTypes.First(s => s.ID == (int)StandardSubmissionStatusTypes.Imported_Published);//imported and published
            var operationalStatus                 = coreRefData.StatusTypes.First(os => os.ID == 50);
            var nonoperationalStatus              = coreRefData.StatusTypes.First(os => os.ID == 100);
            var unknownStatus                     = coreRefData.StatusTypes.First(os => os.ID == (int)StandardStatusTypes.Unknown);
            var usageTypeUnknown                  = coreRefData.UsageTypes.First(u => u.ID == (int)StandardUsageTypes.Unknown);
            var usageTypePublic                   = coreRefData.UsageTypes.First(u => u.ID == (int)StandardUsageTypes.Public);
            var usageTypePublicPayAtLocation      = coreRefData.UsageTypes.First(u => u.ID == (int)StandardUsageTypes.Public_PayAtLocation);
            var usageTypePrivate                  = coreRefData.UsageTypes.First(u => u.ID == (int)StandardUsageTypes.PrivateRestricted);
            var usageTypePublicMembershipRequired = coreRefData.UsageTypes.First(u => u.ID == (int)StandardUsageTypes.Public_MembershipRequired);
            var operatorUnknown                   = coreRefData.Operators.First(opUnknown => opUnknown.ID == (int)StandardOperators.UnknownOperator);

            int itemCount = 0;

            foreach (var dataItem in dataList)
            {
                var         item = dataItem;
                ChargePoint cp   = new ChargePoint();
                cp.DataProvider = new DataProvider()
                {
                    ID = 18
                };                                                //UK National Charge Point Registry
                cp.DataProvidersReference = item["ChargeDeviceId"].ToString();
                cp.DateLastStatusUpdate   = DateTime.UtcNow;
                cp.AddressInfo            = new AddressInfo();

                var locationDetails = item["ChargeDeviceLocation"];
                var addressDetails  = locationDetails["Address"];


                cp.AddressInfo.RelatedURL      = "";
                cp.DateLastStatusUpdate        = DateTime.UtcNow;
                cp.AddressInfo.AddressLine1    = addressDetails["Street"].ToString().Replace("<br>", ", ");
                cp.AddressInfo.Title           = String.IsNullOrEmpty(locationDetails["LocationShortDescription"].ToString()) ? cp.AddressInfo.AddressLine1 : locationDetails["LocationShortDescription"].ToString();
                cp.AddressInfo.Title           = cp.AddressInfo.Title.Replace("&amp;", "&");
                cp.AddressInfo.Title           = cp.AddressInfo.Title.Replace("<br>", ", ");
                cp.AddressInfo.Town            = addressDetails["PostTown"].ToString();
                cp.AddressInfo.StateOrProvince = addressDetails["DependantLocality"].ToString();
                cp.AddressInfo.Postcode        = addressDetails["PostCode"].ToString();
                cp.AddressInfo.Latitude        = double.Parse(locationDetails["Latitude"].ToString());
                cp.AddressInfo.Longitude       = double.Parse(locationDetails["Longitude"].ToString());
                cp.AddressInfo.AccessComments  = locationDetails["LocationLongDescription"].ToString().Replace("<br>", ", ").Replace("\r\n", ", ").Replace("\n", ", ");

                //TODO: if address wasn't provide in address details try to parse from "LocationLongDescription":

                /*if (String.IsNullOrEmpty(cp.AddressInfo.AddressLine1) && string.IsNullOrEmpty(cp.AddressInfo.AddressLine2) && string.IsNullOrEmpty(cp.AddressInfo.Town) && string.IsNullOrEmpty(cp.AddressInfo.Postcode))
                 * {
                 *
                 * }*/

                //if title is empty, attempt to add a suitable replacement
                if (String.IsNullOrEmpty(cp.AddressInfo.Title))
                {
                    if (!String.IsNullOrEmpty(cp.AddressInfo.AddressLine1))
                    {
                        cp.AddressInfo.Title = cp.AddressInfo.AddressLine1;
                    }
                    else
                    {
                        cp.AddressInfo.Title = cp.AddressInfo.Postcode;
                    }
                }
                //cp.AddressInfo.ContactTelephone1 = item["phone"].ToString();

                if (!String.IsNullOrEmpty(addressDetails["Country"].ToString()))
                {
                    string country   = addressDetails["Country"].ToString();
                    int?   countryID = null;

                    var countryVal = coreRefData.Countries.FirstOrDefault(c => c.Title.ToLower() == country.Trim().ToLower());
                    if (countryVal == null)
                    {
                        country = country.ToUpper();
                        //match country
                        if (country == "gb" || country == "US" || country == "USA" || country == "U.S." || country == "U.S.A.")
                        {
                            countryID = 2;
                        }
                        if (country == "UK" || country == "GB" || country == "GREAT BRITAIN" || country == "UNITED KINGDOM")
                        {
                            countryID = 1;
                        }
                    }
                    else
                    {
                        countryID = countryVal.ID;
                    }

                    if (countryID == null)
                    {
                        this.Log("Country Not Matched, will require Geolocation:" + item["country"].ToString());
                    }
                    else
                    {
                        cp.AddressInfo.Country = coreRefData.Countries.FirstOrDefault(cy => cy.ID == countryID);
                    }
                }
                else
                {
                    //default to US if no country identified
                    //cp.AddressInfo.Country = cp.AddressInfo.Country = coreRefData.Countries.FirstOrDefault(cy => cy.ID == 2);
                }

                //operator from DeviceController
                var deviceController = item["DeviceController"];

                cp.AddressInfo.RelatedURL = deviceController["Website"].ToString();
                var deviceOperator = coreRefData.Operators.FirstOrDefault(devOp => devOp.Title.Contains(deviceController["OrganisationName"].ToString()));
                if (deviceOperator != null)
                {
                    cp.OperatorInfo = deviceOperator;
                }
                else
                {
                    //operator from device owner
                    var devOwner = item["DeviceOwner"];
                    deviceOperator = coreRefData.Operators.FirstOrDefault(devOp => devOp.Title.Contains(devOwner["OrganisationName"].ToString()));
                    if (deviceOperator != null)
                    {
                        cp.OperatorInfo = deviceOperator;
                    }
                }

                //determine most likely usage type
                cp.UsageType = usageTypeUnknown;

                if (item["SubscriptionRequiredFlag"].ToString().ToUpper() == "TRUE")
                {
                    //membership required
                    cp.UsageType = usageTypePublicMembershipRequired;
                }
                else
                {
                    if (item["PaymentRequiredFlag"].ToString().ToUpper() == "TRUE")
                    {
                        //payment required
                        cp.UsageType = usageTypePublicPayAtLocation;
                    }
                    else
                    {
                        //accessible 24 hours, payment not required and membership not required, assume public
                        if (item["Accessible24Hours"].ToString().ToUpper() == "TRUE")
                        {
                            cp.UsageType = usageTypePublic;
                        }
                    }
                }

                //add connections
                var connectorList = item["Connector"].ToArray();
                foreach (var conn in connectorList)
                {
                    string connectorType = conn["ConnectorType"].ToString();
                    if (!String.IsNullOrEmpty(connectorType))
                    {
                        ConnectionInfo cinfo = new ConnectionInfo()
                        {
                        };
                        ConnectionType cType = new ConnectionType {
                            ID = 0
                        };
                        ChargerType level = null;
                        cinfo.Reference = conn["ConnectorId"].ToString();

                        if (connectorType.ToUpper().Contains("BS 1363"))
                        {
                            cType    = new ConnectionType();
                            cType.ID = 3; //UK 13 amp plug
                            level    = new ChargerType {
                                ID = 2
                            };                                 //default to level 2
                        }

                        if (connectorType.ToUpper() == "IEC 62196-2 TYPE 1 (SAE J1772)")
                        {
                            cType    = new ConnectionType();
                            cType.ID = 2; //J1772
                            level    = new ChargerType {
                                ID = 2
                            };                                 //default to level 2
                        }

                        if (connectorType.ToUpper() == "IEC 62196-2 TYPE 2")
                        {
                            cType    = new ConnectionType();
                            cType.ID = 25; //Mennkes Type 2
                            level    = new ChargerType {
                                ID = 2
                            };                                 //default to level 2
                        }

                        if (connectorType.ToUpper() == "JEVS G 105 (CHADEMO)")
                        {
                            cType    = new ConnectionType();
                            cType.ID = 2; //CHadeMO
                            level    = new ChargerType {
                                ID = 3
                            };                                 //default to level 3
                        }
                        if (connectorType.ToUpper() == "IEC 62196-2 TYPE 3")
                        {
                            cType    = new ConnectionType();
                            cType.ID = 26; //IEC 62196-2 type 3

                            level = new ChargerType {
                                ID = 2
                            };                                 //default to level 2
                        }

                        if (cType.ID == 0)
                        {
                            var conType = coreRefData.ConnectionTypes.FirstOrDefault(ct => ct.Title.ToLower().Contains(conn.ToString().ToLower()));
                            if (conType != null)
                            {
                                cType = conType;
                            }
                        }

                        if (!String.IsNullOrEmpty(conn["RatedOutputVoltage"].ToString()))
                        {
                            cinfo.Voltage = int.Parse(conn["RatedOutputVoltage"].ToString());
                        }
                        if (!String.IsNullOrEmpty(conn["RatedOutputCurrent"].ToString()))
                        {
                            cinfo.Amps = int.Parse(conn["RatedOutputCurrent"].ToString());
                        }
                        //TODO: use AC/DC/3 Phase data

                        if (conn["ChargePointStatus"] != null)
                        {
                            cinfo.StatusType = operationalStatus;
                            if (conn["ChargePointStatus"].ToString() == "Out of service")
                            {
                                cinfo.StatusType = nonoperationalStatus;
                            }
                        }

                        if (conn["RatedOutputkW"] != null)
                        {
                            double tmpKw = 0;
                            if (double.TryParse(conn["RatedOutputkW"].ToString(), out tmpKw))
                            {
                                cinfo.PowerKW = tmpKw;
                            }
                        }

                        if (conn["RatedOutputVoltage"] != null)
                        {
                            int tmpV = 0;
                            if (int.TryParse(conn["RatedOutputVoltage"].ToString(), out tmpV))
                            {
                                cinfo.Voltage = tmpV;
                            }
                        }

                        if (conn["RatedOutputCurrent"] != null)
                        {
                            int tmpA = 0;
                            if (int.TryParse(conn["RatedOutputCurrent"].ToString(), out tmpA))
                            {
                                cinfo.Amps = tmpA;
                            }
                        }

                        if (conn["ChargeMethod"] != null && !String.IsNullOrEmpty(conn["ChargeMethod"].ToString()))
                        {
                            string method = conn["ChargeMethod"].ToString();
                            //Single Phase AC, Three Phase AC, DC
                            if (method == "Single Phase AC")
                            {
                                cinfo.CurrentTypeID = (int)StandardCurrentTypes.SinglePhaseAC;
                            }
                            if (method == "Three Phase AC")
                            {
                                cinfo.CurrentTypeID = (int)StandardCurrentTypes.ThreePhaseAC;
                            }
                            if (method == "DC")
                            {
                                cinfo.CurrentTypeID = (int)StandardCurrentTypes.DC;
                            }
                        }
                        cinfo.ConnectionType = cType;
                        cinfo.Level          = level;

                        if (cp.Connections == null)
                        {
                            cp.Connections = new List <ConnectionInfo>();
                            if (!IsConnectionInfoBlank(cinfo))
                            {
                                //TODO: skip items with blank address info
                                cp.Connections.Add(cinfo);
                            }
                        }
                    }
                }

                //apply data attribution metadata
                if (cp.MetadataValues == null)
                {
                    cp.MetadataValues = new List <MetadataValue>();
                }
                cp.MetadataValues.Add(new MetadataValue {
                    MetadataFieldID = (int)StandardMetadataFields.Attribution, ItemValue = DataAttribution
                });

                if (cp.DataQualityLevel == null)
                {
                    cp.DataQualityLevel = 3;
                }

                cp.SubmissionStatus = submissionStatus;

                outputList.Add(cp);
                itemCount++;
            }

            return(outputList);
        }
Esempio n. 11
0
        public MSmzML Produce(string path, ProgressUpdate updater, AveragineType type, ChargerType charger)
        {
            var model = new MSmzML();

            // cvList
            model.cvList = new CVList();
            CV[] cvArray = new CV[2];
            cvArray[0] = new CV()
            {
                id       = "MS",
                fullName = "Proteomics Standards Initiative Mass Spectrometry Ontology",
                version  = "2.26.0",
                URI      = "http://psidev.cvs.sourceforge.net/*checkout*/psidev/psi/psi-ms/mzML/controlledVocabulary/psi-ms.obo"
            };
            cvArray[1] = new CV
            {
                id       = "UO",
                fullName = "Unit Ontology",
                version  = "14:07:2009",
                URI      = "http://obo.cvs.sourceforge.net/*checkout*/obo/obo/ontology/phenotype/unit.obo"
            };
            model.cvList.cv    = cvArray;
            model.cvList.count = "2";

            // fileDescription
            model.fileDescription                        = new FileDescription();
            model.fileDescription.fileContent            = new FileContent();
            model.fileDescription.fileContent.cvParam    = new CVParam[2];
            model.fileDescription.fileContent.cvParam[0] = new CVParam
            {
                cvRef     = "MS",
                accession = "MS:1000580",
                name      = "MSn spectrum",
                value     = ""
            };
            model.fileDescription.fileContent.cvParam[1] = new CVParam
            {
                cvRef     = "MS",
                accession = "MS:1000127",
                name      = "centroid spectrum",
                value     = ""
            };
            model.fileDescription.sourceFileList            = new SourceFileList();
            model.fileDescription.sourceFileList.sourceFile = new SourceFile[1];
            string fileName = Path.GetFileName(path);

            model.fileDescription.sourceFileList.sourceFile[0] = new SourceFile
            {
                id       = fileName,
                name     = fileName,
                location = path
            };
            model.fileDescription.sourceFileList.count = "1";
            model.fileDescription.contact            = new Contact();
            model.fileDescription.contact.cvParam    = new CVParam[2];
            model.fileDescription.contact.cvParam[0] = new CVParam
            {
                cvRef     = "MS",
                accession = "MS:1000586",
                name      = "contact name",
                value     = contactPerson
            };
            model.fileDescription.contact.cvParam[1] = new CVParam
            {
                cvRef     = "MS",
                accession = "MS:1000589",
                name      = "contact email",
                value     = contactEmail
            };

            // softwareList
            model.softwareList             = new SoftwareList();
            model.softwareList.software    = new Software[1];
            model.softwareList.software[0] = new Software
            {
                id      = software,
                version = softwareVersion
            };
            model.softwareList.count = "1";

            // instrumentConfiguration
            string instrumentConfigurationID = "UNKNOWN";

            model.instrumentConfigurationList = new InstrumentConfigurationList();
            model.instrumentConfigurationList.instrumentConfiguration    = new InstrumentConfiguration[1];
            model.instrumentConfigurationList.instrumentConfiguration[0] = new InstrumentConfiguration()
            {
                id = instrumentConfigurationID
            };
            model.instrumentConfigurationList.count = "1";

            // data processing
            model.dataProcessingList = new DataProcessingList();
            model.dataProcessingList.dataProcessing       = new DataProcessing[1];
            model.dataProcessingList.dataProcessing[0]    = new DataProcessing();
            model.dataProcessingList.dataProcessing[0].id = dataProcessingID;
            model.dataProcessingList.dataProcessing[0].processingMethod    = new ProcessingMethod[1];
            model.dataProcessingList.dataProcessing[0].processingMethod[0] = new ProcessingMethod()
            {
                order       = "1",
                softwareRef = software
            };
            model.dataProcessingList.dataProcessing[0].processingMethod[0].cvParam    = new CVParam[2];
            model.dataProcessingList.dataProcessing[0].processingMethod[0].cvParam[0] = new CVParam()
            {
                cvRef     = "MS",
                accession = "MS:1000035",
                name      = "peak picking",
                value     = ""
            };
            model.dataProcessingList.dataProcessing[0].processingMethod[0].cvParam[1] = new CVParam()
            {
                cvRef     = "MS",
                accession = "MS:1000544",
                name      = "Conversion to mzML",
                value     = ""
            };
            model.dataProcessingList.count = "1";

            // spectrum data
            ThermoRawRunFactory factory = new ThermoRawRunFactory();

            model.run = factory.Read(path, type, charger,
                                     model.dataProcessingList.dataProcessing[0].id, updater);
            model.run.id = Guid.NewGuid().ToString();
            model.run.defaultInstrumentConfigurationRef = instrumentConfigurationID;
            return(model);
        }
        public static Spectrum GetMS2Spectrum(ref ThermoRawSpectrumReader reader,
                                              int scan, AveragineType type, ChargerType chargerType, LocalMaximaPicking picking, IProcess process,
                                              ISpectrum ms1)
        {
            // scan header
            Spectrum spectrum = new Spectrum
            {
                id = "scan=" + scan.ToString()
            };

            double dLowMass           = 0;
            double dHighMass          = 0;
            double dTIC               = 0;
            double dBasePeakMass      = 0;
            double dBasePeakIntensity = 0;

            reader.GetScanHeaderInfoForScanNum(scan, ref dLowMass, ref dHighMass,
                                               ref dTIC, ref dBasePeakMass, ref dBasePeakIntensity);
            SetScanHeader(spectrum, dLowMass, dHighMass, dTIC,
                          dBasePeakMass, dBasePeakIntensity);

            // binary data
            spectrum.binaryDataArrayList = new BinaryDataArrayList();
            SetBinaryDataArrayHeader(spectrum.binaryDataArrayList);

            spectrum.cvParam[0] = new Component.CVParam()
            {
                cvRef     = "MS",
                accession = "MS:1000511",
                name      = "ms level",
                value     = "2",
            };

            double       mz       = reader.GetPrecursorMass(scan, reader.GetMSnOrder(scan));
            List <IPeak> ms1Peaks = FilterPeaks(ms1.GetPeaks(), mz, searchRange);

            if (ms1Peaks.Count() == 0)
            {
                return(null);
            }

            // insert pseudo peaks for large gaps
            List <IPeak> peaks     = new List <IPeak>();
            double       precision = 0.02;
            double       last      = ms1Peaks.First().GetMZ();

            foreach (IPeak peak in ms1Peaks)
            {
                if (peak.GetMZ() - last > precision)
                {
                    peaks.Add(new GeneralPeak(last + precision / 2, 0));
                    peaks.Add(new GeneralPeak(peak.GetMZ() - precision / 2, 0));
                }
                peaks.Add(peak);
                last = peak.GetMZ();
            }
            List <IPeak> majorPeaks = picking.Process(peaks);
            ICharger     charger    = new Patterson();

            if (chargerType == ChargerType.Fourier)
            {
                charger = new Fourier();
            }
            else if (chargerType == ChargerType.Combined)
            {
                charger = new PattersonFourierCombine();
            }
            int charge = charger.Charge(peaks, mz - searchRange, mz + searchRange);

            // find evelope cluster
            EnvelopeProcess envelope = new EnvelopeProcess();
            var             cluster  = envelope.Cluster(majorPeaks, mz, charge);

            if (cluster.Count == 0)
            {
                return(null);
            }

            // find monopeak
            Averagine            averagine = new Averagine(type);
            BrainCSharp          braincs   = new BrainCSharp();
            MonoisotopicSearcher searcher  = new MonoisotopicSearcher(averagine, braincs);
            MonoisotopicScore    result    = searcher.Search(mz, charge, cluster);

            // process spectrum
            ISpectrum ms2 = reader.GetSpectrum(scan);

            List <IPeak> ms2Peaks = process.Process(ms2).GetPeaks();

            spectrum.binaryDataArrayList.binaryDataArray[0].binary =
                ms2Peaks.SelectMany(p => BitConverter.GetBytes(p.GetMZ())).ToArray();
            spectrum.binaryDataArrayList.binaryDataArray[1].binary =
                ms2Peaks.SelectMany(p => BitConverter.GetBytes(p.GetIntensity())).ToArray();
            spectrum.defaultArrayLength = ms2Peaks.Count.ToString();

            spectrum.precursorList = new PrecursorList
            {
                count     = "1",
                precursor = new Precursor[1]
            };
            for (int i = 0; i < spectrum.precursorList.precursor.Length; i++)
            {
                spectrum.precursorList.precursor[i] = new Precursor();
            }

            spectrum.precursorList.precursor[0].selectedIonList = new SelectedIonList
            {
                count       = "1",
                selectedIon = new SelectedIon[1]
            };
            for (int i = 0; i < spectrum.precursorList.precursor[0].selectedIonList.selectedIon.Length; i++)
            {
                spectrum.precursorList.precursor[0].selectedIonList.selectedIon[i] = new SelectedIon();
            }
            spectrum.precursorList.precursor[0].selectedIonList.selectedIon[0].cvParam    = new Component.CVParam[2];
            spectrum.precursorList.precursor[0].selectedIonList.selectedIon[0].cvParam[0] = new Component.CVParam()
            {
                cvRef         = "MS",
                accession     = "MS:1000744",
                name          = "selected ion m/z",
                value         = result.GetMZ().ToString(),
                unitCvRef     = "MS",
                unitAccession = "MS:1000040",
                unitName      = "m/z"
            };
            spectrum.precursorList.precursor[0].selectedIonList.selectedIon[0].cvParam[1] = new Component.CVParam()
            {
                cvRef     = "MS",
                accession = "MS:1000041",
                name      = "charge state",
                value     = charge.ToString()
            };
            spectrum.precursorList.precursor[0].activation = new Activation
            {
                cvParam = new Component.CVParam[1]
            };
            spectrum.precursorList.precursor[0].activation.cvParam[0] =
                ActivationCVParam(reader.GetActivation(scan));

            spectrum.binaryDataArrayList.binaryDataArray[0].encodedLength =
                Convert.ToBase64String(spectrum.binaryDataArrayList.binaryDataArray[0].binary).Length.ToString();
            spectrum.binaryDataArrayList.binaryDataArray[1].encodedLength =
                Convert.ToBase64String(spectrum.binaryDataArrayList.binaryDataArray[1].binary).Length.ToString();
            return(spectrum);
        }