public void different_classes_with_same_id_value_should_not_be_equal()
        {
            var a = new SampleId("a");
            var b = new AnotherSampleId("a");

            Assert.IsFalse(a.Equals(b));
        }
Beispiel #2
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (SampleId != 0UL)
            {
                hash ^= SampleId.GetHashCode();
            }
            hash ^= data_.GetHashCode();
            return(hash);
        }
        public void test_equality()
        {
            var a = new SampleId("a");
            var b = new SampleId("a");

            Assert.AreEqual(a, b);
            Assert.IsTrue(a.Equals(b));

            Assert.IsTrue(a.Equals(a));
            Assert.IsTrue(a == b);
        }
        public void test_inequality()
        {
            var a = new SampleId("a");
            var b = new SampleId("b");

            Assert.AreNotEqual(a, null);
            Assert.AreNotEqual(a, b);

            Assert.IsFalse(a.Equals(b));
            Assert.IsFalse(a.Equals(null));

            Assert.IsFalse(a == b);
        }
        private static ReferencePloidy LoadReferencePloidy(IEnumerable <ReferencePloidyInterval> ploidyVcfIntervals,
                                                           bool useSymbolicAltAlleleInPloidyVcf = true)
        {
            var sampleId = new SampleId("sampleId");
            var vcf      = GetVcfAsString(sampleId, ploidyVcfIntervals, useSymbolicAltAlleleInPloidyVcf);

            using (var textReader = new StringReader(vcf))
                using (var reader = new GzipOrTextReader(textReader))
                    using (var vcfReader = new VcfReader(reader))
                    {
                        return(ReferencePloidy.Load(vcfReader, sampleId));
                    }
        }
Beispiel #6
0
 public SoundEffectEvent(
     SampleId soundId,
     byte volume,
     byte restartProbability,
     byte unk3,
     ushort frequencyOverride,
     SoundMode mode)
 {
     SoundId            = soundId;
     Volume             = volume;
     RestartProbability = restartProbability;
     Unk3 = unk3;
     FrequencyOverride = frequencyOverride;
     Mode = mode;
 }
        public static bool IsSharedCnv(ISampleMap <Genotype> copyNumberGenotypes, ISampleMap <CanvasSegment> canvasSegments, ISampleMap <SampleMetrics> samplesInfo, List <SampleId> parentIDs,
                                       SampleId probandId, int maximumCopyNumber)
        {
            var proband = copyNumberGenotypes[probandId];
            var parent1 = copyNumberGenotypes[parentIDs.First()];
            var parent2 = copyNumberGenotypes[parentIDs.Last()];

            if (proband.PhasedGenotype == null)
            {
                return(IsSharedCnv(canvasSegments, samplesInfo, parentIDs, probandId, maximumCopyNumber));
            }

            return((proband.PhasedGenotype.ContainsSharedAlleleA(parent1.PhasedGenotype) &&
                    proband.PhasedGenotype.ContainsSharedAlleleB(parent2.PhasedGenotype)) ||
                   (proband.PhasedGenotype.ContainsSharedAlleleA(parent2.PhasedGenotype) &&
                    proband.PhasedGenotype.ContainsSharedAlleleB(parent1.PhasedGenotype)));
        }
        private static string GetVcfAsString(SampleId sampleId, IEnumerable <ReferencePloidyInterval> intervals, bool symbolicAllele)
        {
            var vcf =
                "##fileformat=VCFv4.1\n" +
                $"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tS1\t{sampleId}\tS3\n";

            foreach (var interval in intervals)
            {
                var position = symbolicAllele
                    ? interval.Interval.Interval.OneBasedStart - 1
                    : interval.Interval.Interval.OneBasedStart;
                var altAllele = symbolicAllele ? "<CNV>" : ".";

                vcf +=
                    $"{interval.Interval.Chromosome}\t{position}\t.\tN\t{altAllele}\t.\tPASS\tEND={interval.Interval.Interval.OneBasedEnd}\tCN\t.\t{interval.ReferencePloidy}\t.\n";
            }
            return(vcf);
        }
        /// <summary>
        /// identify common variants using total CN calls within a pedigree obtained with coverage information only
        /// </summary>
        /// <param name="canvasSegments"></param>
        /// <param name="samplesInfo"></param>
        /// <param name="parentIDs"></param>
        /// <param name="probandId"></param>
        /// <param name="maximumCopyNumber"></param>
        /// <returns></returns>
        public static bool IsSharedCnv(ISampleMap <CanvasSegment> canvasSegments, ISampleMap <SampleMetrics> samplesInfo, List <SampleId> parentIDs,
                                       SampleId probandId, int maximumCopyNumber)
        {
            int parent1CopyNumber = Math.Min(canvasSegments[parentIDs.First()].CopyNumber, maximumCopyNumber - 1);
            int parent2CopyNumber = Math.Min(canvasSegments[parentIDs.Last()].CopyNumber, maximumCopyNumber - 1);
            int probandCopyNumber = Math.Min(canvasSegments[probandId].CopyNumber, maximumCopyNumber - 1);
            var parent1Segment    = canvasSegments[parentIDs.First()];
            var parent2Segment    = canvasSegments[parentIDs.Last()];
            var probandSegment    = canvasSegments[probandId];
            int parent1Ploidy     = samplesInfo[parentIDs.First()].GetPloidy(parent1Segment);
            int parent2Ploidy     = samplesInfo[parentIDs.Last()].GetPloidy(parent2Segment);
            int probandPloidy     = samplesInfo[probandId].GetPloidy(probandSegment);

            // Use the following logic: if the proband has fewer copies than expected (from ploidy) but both parents have at least the expected number of copies OR the
            // proband has more copies than expected but both parents have no more than the expected number of copies,
            // then it is not a 'common CNV' (i.e.it could be de novo); otherwise, it is common
            return(!(parent1CopyNumber <= parent1Ploidy && parent2CopyNumber <= parent2Ploidy && probandCopyNumber > probandPloidy ||
                     parent1CopyNumber >= parent1Ploidy && parent2CopyNumber >= parent2Ploidy && probandCopyNumber < probandPloidy));
        }
Beispiel #10
0
 public static void WriteSegments(string outVcfPath, List <CanvasSegment> segments, double?diploidCoverage,
                                  string wholeGenomeFastaDirectory, string sampleName,
                                  List <string> extraHeaders, PloidyInfo ploidy, int qualityThreshold, bool isPedigreeInfoSupplied, int?denovoQualityThreshold, int?sizeThreshold)
 {
     using (BgzipOrStreamWriter writer = new BgzipOrStreamWriter(outVcfPath))
     {
         var genome = WriteVcfHeader(segments, diploidCoverage, wholeGenomeFastaDirectory, new List <string> {
             sampleName
         },
                                     extraHeaders, writer, qualityThreshold, denovoQualityThreshold, sizeThreshold);
         var sampleId             = new SampleId(sampleName);
         var segmentsOfAllSamples = segments.Select(x => new SampleMap <CanvasSegment> {
             { sampleId, x }
         });
         WriteVariants(segmentsOfAllSamples, new List <PloidyInfo> {
             ploidy
         }, genome, writer, denovoQualityThreshold);
     }
 }
Beispiel #11
0
 public static SoundEvent Serdes(SoundEvent e, AssetMapping mapping, ISerializer s)
 {
     if (s == null)
     {
         throw new ArgumentNullException(nameof(s));
     }
     e ??= new SoundEvent();
     e.Mode               = s.EnumU8(nameof(Mode), e.Mode);
     e.SoundId            = SampleId.SerdesU8(nameof(SoundId), e.SoundId, mapping, s);
     e.Unk3               = s.UInt8(nameof(Unk3), e.Unk3);
     e.Volume             = s.UInt8(nameof(Volume), e.Volume);
     e.RestartProbability = s.UInt8(nameof(RestartProbability), e.RestartProbability);
     e.FrequencyOverride  = s.UInt16(nameof(FrequencyOverride), e.FrequencyOverride);
     e.Unk8               = s.UInt16(nameof(Unk8), e.Unk8);
     ApiUtil.Assert(e.Unk3 <= 100);
     ApiUtil.Assert(e.Volume <= 150);
     ApiUtil.Assert(e.RestartProbability <= 102);
     ApiUtil.Assert(e.Unk8 == 0);
     return(e);
 }
Beispiel #12
0
    public static SoundEvent Serdes(SoundEvent e, AssetMapping mapping, ISerializer s)
    {
        if (s == null)
        {
            throw new ArgumentNullException(nameof(s));
        }
        e ??= new SoundEvent();
        e.Mode               = s.EnumU8(nameof(Mode), e.Mode);
        e.SoundId            = SampleId.SerdesU8(nameof(SoundId), e.SoundId, mapping, s);
        e.Unk3               = s.UInt8(nameof(Unk3), e.Unk3);
        e.Volume             = s.UInt8(nameof(Volume), e.Volume);
        e.RestartProbability = s.UInt8(nameof(RestartProbability), e.RestartProbability);
        e.FrequencyOverride  = s.UInt16(nameof(FrequencyOverride), e.FrequencyOverride);
        int zeroed = s.UInt16(null, 0);

        s.Assert(e.Unk3 <= 100, "SoundEvent: Expected unk3 to be <= 100");
        s.Assert(e.Volume <= 150, "SoundEvent: Expected volume to be <= 150");
        s.Assert(e.RestartProbability <= 102, "SoundEvent: Expected restart probability to be <= 102");
        s.Assert(zeroed == 0, "SoundEvent: Expected field 8 to be 0");
        return(e);
    }
Beispiel #13
0
        internal int CallVariants(List <string> variantFrequencyFiles, List <string> segmentFiles,
                                  IFileLocation outVcfFile, string ploidyBedPath, string referenceFolder, List <string> sampleNames, string commonCnvsBedPath, List <SampleType> sampleTypes)
        {
            // load files
            // initialize data structures and classes
            var fileCounter      = 0;
            var samplesInfo      = new SampleMap <SampleMetrics>();
            var sampleSegments   = new SampleMap <Segments>();
            var copyNumberModels = new SampleMap <ICopyNumberModel>();
            var variantFrequencyFilesSampleList = new SampleMap <string>();
            var kinships = new SampleMap <SampleType>();

            foreach (string sampleName in sampleNames)
            {
                var sampleId = new SampleId(sampleName);
                var segment  = Segments.ReadSegments(_logger, new FileLocation(segmentFiles[fileCounter]));
                segment.AddAlleles(CanvasIO.ReadFrequenciesWrapper(_logger, new FileLocation(variantFrequencyFiles[fileCounter]), segment.IntervalsByChromosome));
                sampleSegments.Add(sampleId, segment);
                var sampleInfo      = SampleMetrics.GetSampleInfo(segment.AllSegments, ploidyBedPath, _callerParameters.NumberOfTrimmedBins, sampleId);
                var copyNumberModel = _copyNumberModelFactory.CreateModel(_callerParameters.MaximumCopyNumber, sampleInfo.MaxCoverage, sampleInfo.MeanCoverage, sampleInfo.MeanMafCoverage);
                samplesInfo.Add(sampleId, sampleInfo);
                copyNumberModels.Add(sampleId, copyNumberModel);
                variantFrequencyFilesSampleList.Add(sampleId, variantFrequencyFiles[fileCounter]);
                kinships.Add(sampleId, sampleTypes[fileCounter]);
                fileCounter++;
            }
            var segmentSetsFromCommonCnvs = CreateSegmentSetsFromCommonCnvs(variantFrequencyFilesSampleList,
                                                                            _callerParameters.MinAlleleCountsThreshold, commonCnvsBedPath, sampleSegments);

            var          segmentsForVariantCalling = GetHighestLikelihoodSegments(segmentSetsFromCommonCnvs, samplesInfo, copyNumberModels).ToList();
            PedigreeInfo pedigreeInfo = PedigreeInfo.GetPedigreeInfo(kinships, _callerParameters);

            Parallel.ForEach(
                segmentsForVariantCalling,
                new ParallelOptions
            {
                MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, _callerParameters.MaxCoreNumber)
            },
                segments => _variantCaller.CallVariant(segments, samplesInfo, copyNumberModels, pedigreeInfo)
                );
            var variantCalledSegments = new SampleMap <List <CanvasSegment> >();

            foreach (var key in samplesInfo.SampleIds)
            {
                variantCalledSegments.Add(key, segmentsForVariantCalling.Select(segment => segment[key]).ToList());
            }

            var mergedVariantCalledSegments = MergeSegments(variantCalledSegments, _callerParameters.MinimumCallSize, _qualityFilterThreshold);

            FilterExcessivelyShortSegments(mergedVariantCalledSegments);

            var outputFolder = outVcfFile.Directory;

            foreach (var sampleId in samplesInfo.SampleIds)
            {
                var coverageOutputPath = SingleSampleCallset.GetCoverageAndVariantFrequencyOutput(outputFolder,
                                                                                                  sampleId.ToString());
                CanvasSegment.WriteCoveragePlotData(mergedVariantCalledSegments[sampleId], samplesInfo[sampleId].MeanCoverage,
                                                    samplesInfo[sampleId].Ploidy, coverageOutputPath, referenceFolder);
            }
            bool isPedigreeInfoSupplied = pedigreeInfo != null && pedigreeInfo.HasFullPedigree();
            var  denovoQualityThreshold = isPedigreeInfoSupplied ? (int?)_deNovoQualityFilterThreshold : null;
            var  ploidies        = samplesInfo.Select(info => info.Value.Ploidy).ToList();
            var  diploidCoverage = samplesInfo.Select(info => info.Value.MeanCoverage).ToList();
            var  names           = samplesInfo.SampleIds.Select(id => id.ToString()).ToList();

            CanvasSegmentWriter.WriteMultiSampleSegments(outVcfFile.FullName, mergedVariantCalledSegments, diploidCoverage, referenceFolder, names,
                                                         null, ploidies, _qualityFilterThreshold, denovoQualityThreshold, CanvasFilter.SegmentSizeCutoff, isPedigreeInfoSupplied);

            foreach (var sampleId in samplesInfo.SampleIds)
            {
                var outputVcfPath = SingleSampleCallset.GetVcfOutput(outputFolder, sampleId.ToString());
                var sampleMetrics = samplesInfo[sampleId];
                var segments      = mergedVariantCalledSegments[sampleId];
                CanvasSegmentWriter.WriteSegments(outputVcfPath.FullName, segments,
                                                  sampleMetrics.MeanCoverage, referenceFolder, sampleId.ToString(), null,
                                                  sampleMetrics.Ploidy, _qualityFilterThreshold, isPedigreeInfoSupplied, denovoQualityThreshold, null);

                var visualizationTemp   = outputFolder.CreateSubdirectory($"VisualizationTemp{sampleId}");
                var normalizationFactor = NormalizationCalculator.ComputeNormalizationFactor(segments);
                var bigWig = _coverageBigWigWriter.Write(segments, visualizationTemp, normalizationFactor);
                bigWig?.MoveTo(SingleSampleCallset.GetCoverageBigWig(outputFolder, sampleId.ToString()));
                var copyNumberBedGraph = SingleSampleCallset.GetCopyNumberBedGraph(outputFolder, sampleId.ToString());
                _copyNumberBedGraphWriter.Write(segments, sampleMetrics.Ploidy, copyNumberBedGraph);

                var partitionBedgraphHeader = "track type=bedGraph visibility=full autoScale=on graphType=points";
                var originalSegments        = sampleSegments[sampleId];
                _partitionCoverageBedGraphWriter.Write(originalSegments.AllSegments, SingleSampleCallset.GetPartitionBedGraph(outputFolder, sampleId.ToString()), normalizationFactor, partitionBedgraphHeader);
            }
            return(0);
        }
Beispiel #14
0
        public Sample(SampleId sampleId)
        {
            var @event = new SampleCreated(sampleId);

            Apply(@event);
        }
Beispiel #15
0
        /// <summary>
        /// Assess likelihood of a de-novo variant for copyNumberGenotypes configuration with a Mendelian conflict
        /// </summary>
        /// <param name="canvasSegments"></param>
        /// <param name="jointLikelihoods"></param>
        /// <param name="parentIDs"></param>
        /// <param name="probandId"></param>
        /// <param name="samplesInfo"></param>
        /// <returns></returns>
        internal static double GetConditionalDeNovoQualityScore(ISampleMap <CanvasSegment> canvasSegments, JointLikelihoods jointLikelihoods, ISampleMap <SampleMetrics> samplesInfo, List <SampleId> parentIDs, SampleId probandId)
        {
            const double q60           = 0.000001;
            var          parent1Ploidy = Genotype.Create(samplesInfo[parentIDs.First()].GetPloidy(canvasSegments[parentIDs.First()]));
            var          parent2Ploidy = Genotype.Create(samplesInfo[parentIDs.Last()].GetPloidy(canvasSegments[parentIDs.Last()]));
            int          probandPloidy = samplesInfo[probandId].GetPloidy(canvasSegments[probandId]);

            double deNovoGainMarginalLikelihood = jointLikelihoods.GetMarginalGainDeNovoLikelihood(new KeyValuePair <SampleId, Genotype>(probandId, Genotype.Create(probandPloidy)),
                                                                                                   new KeyValuePair <SampleId, Genotype>(parentIDs.First(), parent1Ploidy), new KeyValuePair <SampleId, Genotype>(parentIDs.Last(), parent2Ploidy));
            double deNovoLossMarginalLikelihood = jointLikelihoods.GetMarginalLossDeNovoLikelihood(new KeyValuePair <SampleId, Genotype>(probandId, Genotype.Create(probandPloidy)),
                                                                                                   new KeyValuePair <SampleId, Genotype>(parentIDs.First(), parent1Ploidy), new KeyValuePair <SampleId, Genotype>(parentIDs.Last(), parent2Ploidy));
            double denovoProbability = canvasSegments[probandId].CopyNumber > probandPloidy ?
                                       1 - deNovoGainMarginalLikelihood / (jointLikelihoods.TotalMarginalLikelihood - deNovoLossMarginalLikelihood) :
                                       1 - deNovoLossMarginalLikelihood / (jointLikelihoods.TotalMarginalLikelihood - deNovoGainMarginalLikelihood);

            // likelihood of proband genotype != ALT given "copyNumberGenotypes" configuration in pedigree with Mendelian conflict
            return(-10.0 * Math.Log10(Math.Max(denovoProbability, q60)));
        }
Beispiel #16
0
 public Sample(SampleId experienceId, Volume volume)
 {
     Apply(new SampleCreated(experienceId, volume));
 }
Beispiel #17
0
 private static int GetCnState(ISampleMap <CanvasSegment> canvasSegmentsSet, SampleId sampleId, int maximumCopyNumber)
 {
     return(Math.Min(canvasSegmentsSet[sampleId].CopyNumber, maximumCopyNumber - 1));
 }
Beispiel #18
0
        private bool IsReferenceVariant(ISampleMap <CanvasSegment> canvasSegments, ISampleMap <SampleMetrics> samplesInfo, SampleId sampleId)
        {
            var segment = canvasSegments[sampleId];

            return(GetCnState(canvasSegments, sampleId, _callerParameters.MaximumCopyNumber) == samplesInfo[sampleId].GetPloidy(segment));
        }
Beispiel #19
0
 private bool IsPassVariant(ISampleMap <CanvasSegment> canvasSegments, SampleId sampleId)
 {
     return(canvasSegments[sampleId].QScore >= _qualityFilterThreshold);
 }
Beispiel #20
0
        public IActionResult DodajanjeAlikvotov([FromForm] DodajanjeAlikvotovViewModel alikvot)
        {
            if (alikvot == null)
            {
                return(RedirectToAction("Index"));
            }

            if (alikvot.IdVzorca == null || alikvot.Box == null)
            {
                return(View(alikvot));
            }

            Console.WriteLine(alikvot.IdVzorca);

            var originalSample = _dbContext.Samples.Include(m => m.NewId).First(m => m.NewId.ToString() == alikvot.IdVzorca);

            var startPosition = 0;
            var boxName       = _dbContext.Boxes.First(m => m.BoxName == alikvot.Box);

            if (alikvot.Location != null)
            {
                var column = (int)char.GetNumericValue(alikvot.Location[1]);
                if (alikvot.Location.Length == 3)
                {
                    column = 10 * column + (int)char.GetNumericValue(alikvot.Location[2]);
                }
                startPosition = _rowNames[alikvot.Location[0]] * boxName.Size + column;
            }

            for (var i = 0; i < alikvot.StAlikvotov; i++)
            {
                var id = new SampleId
                {
                    AliquotSequenceNumber          = originalSample.NewId.AliquotSequenceNumber,
                    IsolateType                    = originalSample.NewId.IsolateType,
                    ProcessedAliquotSequenceNumber = originalSample.NewId.ProcessedAliquotSequenceNumber,
                    ProcessedIsolateType           = originalSample.NewId.ProcessedIsolateType,
                    SequenceNumber                 = originalSample.NewId.SequenceNumber,
                    Year = originalSample.NewId.Year
                };
                if (id.AliquotSequenceNumber == 0)
                {
                    id.AliquotSequenceNumber = i + 1;
                }
                else
                {
                    id.ProcessedAliquotSequenceNumber = i + 1;
                }

                if (!alikvot.Volume.HasValue)
                {
                    return(View(alikvot));
                }

                var sample = new Aliquot
                {
                    Volume           = alikvot.VolType == "ml" ? alikvot.Volume.Value : alikvot.Volume.Value / 1000000,
                    AliquotationDate = alikvot.Date ?? DateTime.Now,
                    OriginalSample   = originalSample,
                    NewId            = id
                };
                if (alikvot.Project != null)
                {
                    sample.ProjectName = _dbContext.Projects.FirstOrDefault(m => m.Name == alikvot.Project);
                }

                if (alikvot.Notes != null)
                {
                    sample.Comments = alikvot.Notes;
                }

                if (!alikvot.Razdelek.HasValue)
                {
                    return(View(alikvot));
                }

                var stored = new Storage
                {
                    FridgeName  = _dbContext.Fridges.FirstOrDefault(m => m.Name == alikvot.Fridge),
                    Temperature = alikvot.Temp,
                    Section     = alikvot.Razdelek.Value,
                    BoxName     = boxName,
                    Position    = startPosition + i
                };
                sample.Stored = stored;

                _dbContext.Samples.Add(sample);
            }

            _dbContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
Beispiel #21
0
 public SampleCreated(SampleId id)
 {
     Id = id;
 }
Beispiel #22
0
 public async Task <Sample> Find(SampleId id)
 {
     return(await Context.Samples.FirstOrDefaultAsync(x => x.DatabaseId == id.Value));
 }
        public void null_or_whitespace_id_should_be_invalid(string val)
        {
            var id = new SampleId(val);

            Assert.IsFalse(id.IsValid());
        }
Beispiel #24
0
 public OnlyActiveSampleCanBeCancelledRule(SampleId id, bool isDeleted)
 {
     _id        = id;
     _isDeleted = isDeleted;
 }
Beispiel #25
0
        public static SampleMetrics GetSampleInfo(IReadOnlyList <CanvasSegment> segments, string ploidyBedPath, int numberOfTrimmedBins, SampleId id)
        {
            double meanMafCoverage = new SortedList <int>(segments.SelectMany(x => x.Balleles.TotalCoverage)).Median();
            double variance        = Utilities.Variance(segments.Select(x => x.TruncatedMedianCount(numberOfTrimmedBins)).ToList());
            double mafVariance     = Utilities.Variance(segments.Where(x => x.Balleles.TotalCoverage.Count > 0)
                                                        .Select(x => x.Balleles.TotalCoverage.Average()).ToList());
            double meanCoverage = new SortedList <float>(segments.SelectMany(x => x.Counts).Select(x => x)).Median();
            int    maxCoverage  = Convert.ToInt16(segments.Select(x => x.TruncatedMedianCount(numberOfTrimmedBins)).Max()) + 10;
            var    ploidy       = new PloidyInfo();

            if (!ploidyBedPath.IsNullOrEmpty() && File.Exists(ploidyBedPath))
            {
                ploidy = PloidyInfo.LoadPloidyFromVcfFile(ploidyBedPath, id.ToString());
            }
            return(new SampleMetrics(meanCoverage, meanMafCoverage, variance, mafVariance, maxCoverage, ploidy));
        }
Beispiel #26
0
 public CreateSample(SampleId id)
 {
     Id = id;
 }
Beispiel #27
0
        public IActionResult DodajanjeVzorca([FromForm] DodajanjeVzorcaViewModel vzorec)
        {
            if (vzorec == null)
            {
                return(RedirectToAction("Index"));
            }

            if (vzorec.Fridge == null || !vzorec.Razdelek.HasValue)
            {
                return(View(vzorec));
            }

            Storage stored = new Storage
            {
                FridgeName  = _dbContext.Fridges.FirstOrDefault(m => m.Name == vzorec.Fridge),
                Temperature = vzorec.Temp,
                Section     = vzorec.Razdelek.Value
            };


            if (vzorec.Location != null && vzorec.Box != null)
            {
                stored.BoxName = _dbContext.Boxes.First(m => m.BoxName == vzorec.Box);
                var column = (int)char.GetNumericValue(vzorec.Location[1]);
                if (vzorec.Location.Length == 3)
                {
                    column = 10 * column + (int)char.GetNumericValue(vzorec.Location[2]);
                }
                stored.Position = _rowNames[vzorec.Location[0]] * stored.BoxName.Size + column;
            }

            var sampleType = _dbContext.SampleTypes.FirstOrDefault(m => m.SampleTypeName == vzorec.Type);

            if (_dbContext.Samples.FirstOrDefault(m =>
                                                  m.NewId.Year == (vzorec.DateReception ?? DateTime.Now).Year) == null)
            {
                _sampleValue = 1;
            }
            else
            {
                _sampleValue++;
            }

            var id = new SampleId
            {
                AliquotSequenceNumber          = 0,
                ProcessedAliquotSequenceNumber = 0,
                Year           = (vzorec.DateReception ?? DateTime.Now).Year,
                SequenceNumber = _sampleValue
            };

            if (sampleType != null)
            {
                id.IsolateType = sampleType.ShortName;
            }

            if (!vzorec.Volume.HasValue)
            {
                return(View(vzorec));
            }

            var sample = new Sample
            {
                SubscriberName = vzorec.IdProvider,
                Type           = sampleType,
                Stored         = stored,
                Accepted       = _dbContext.Acceptances.FirstOrDefault(m => m.Date == vzorec.DateReception &&
                                                                       m.SubscriberName ==
                                                                       _dbContext.Subscribers.FirstOrDefault(n =>
                                                                                                             n.Name == vzorec.Provider)),
                NewId  = id,
                Volume = vzorec.VolType == "ml" ? vzorec.Volume.Value : vzorec.Volume.Value / 1000000
            };

            if (vzorec.Project != null)
            {
                sample.ProjectName = _dbContext.Projects.FirstOrDefault(m => m.Name == vzorec.Project);
            }

            if (vzorec.Notes != null)
            {
                sample.Comments = vzorec.Notes;
            }

            if (vzorec.Date != null)
            {
                sample.Time = vzorec.Date ?? DateTime.Now;
            }

            _dbContext.Samples.Add(sample);
            _dbContext.SaveChanges();

            return(RedirectToAction("Index"));
        }