Esempio n. 1
0
    /// <summary>
    /// 序列化csv文件操作.
    /// </summary>
    public static void Save(string filePath, bool checkValid, string dir)
    {
        CsvFile csv = new CsvFile(System.IO.Path.GetFileNameWithoutExtension(filePath));

        string[] lines = FileMgr.ReadLines(filePath);
        if (lines.Length == 0)
        {
            NIDebug.Log("空文件 {0}", lines);
            return;
        }

        // 解析csv文件
        CsvParser cp = new CsvParser();
        LPCValue  m;

        try
        {
            cp.Load(filePath, checkValid);
            if (cp.Fields.Count == 0 || cp.Records.Count == 0)
            {
                return;
            }
            m = ImportMgr.Read(cp);
        }
        catch (Exception e)
        {
            NIDebug.Log("读取csv错误 {0}\n{1}", filePath, e.ToString());
            return;
        }

        // 主key
        csv.primaryKey = cp.PrimaryKey;

        // 列名字对应的索引
        for (int i = 0; i < cp.Fields.Count; i++)
        {
            csv.columns.Add(cp.Fields[i].name, i);
        }

        // 每列值
        csv.rows = new CsvRow[m.AsArray.Count];
        for (int i = 0; i < m.AsArray.Count; i++)
        {
            LPCValue v   = m.AsArray[i];
            CsvRow   row = new CsvRow(csv);
            for (int idx = 0; idx < cp.Fields.Count; idx++)
            {
                row.Add(idx, v.AsMapping[cp.Fields[idx].name]);
            }

            csv.AddRow(i, row);
        }

        // 序列化
        MemoryStream ms = new MemoryStream();

        CsvFileMgr.Serialize(ms, csv);

        // 写入数据
        string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);

        // 确保路径存在
        Directory.CreateDirectory(dir);

        FileStream fs = new FileStream(dir + "/" + fileName + CSV_EXT, FileMode.Create, FileAccess.Write);

        fs.Write(ms.GetBuffer(), 0, (int)ms.Length);
        fs.Close();
    }
Esempio n. 2
0
        public CsvFile GetMetrics(Application app, params StructureQuery[] metricsDesired)
        {
            CsvFile csv    = new CsvFile();
            var     header = new List <dynamic>();

            header.AddRange(new dynamic[] { "Patient Id", "Course", "Plan Id", "Structure", "Volume" });
            var metrics = metricsDesired.SelectMany(m => m.Queries).Distinct().ToList();

            header.AddRange(metrics);

            if (_doIncludeDVH)
            {
                header.Add($"DVH[{_dvhParams.DoseUnits}]");
                header.AddRange(Enumerable.Range(0, 120).Select(i => (dynamic)i));
            }
            csv.AddRow(header.ToArray());

            foreach (var id in _patientIds)
            {
                try
                {
                    Logger.Log($"Opening patient {id}");
                    var pat = app.OpenPatientById(id);
                    if (pat == null)
                    {
                        Logger.Log($"Couldn't find patient {id}");
                        throw new PatientNotFoundException(id);
                    }

                    //Match structure sets
                    Logger.Log($"Filtering structure sets...");
                    var s_structureSets = FilterStructureSets(pat).ToList();
                    Logger.Log($"{s_structureSets.Count()} structure sets match criteria");
                    Logger.Log($"Filtering planning items...");
                    var s_plans = FilterPlanningItems(pat, s_structureSets).ToList();
                    Logger.Log($"{s_plans.Count()} plans match criteria");

                    foreach (var pi in s_plans)
                    {
                        var s_structures = GetFilteredStructures(pi, metricsDesired);
                        foreach (var str in s_structures)
                        {
                            List <dynamic> rowItems = new List <dynamic>();
                            rowItems.AddRange(new dynamic[] { pat.Id, pi.GetCourse().Id, pi.Id });
                            rowItems.Add(str.Id);
                            rowItems.Add(str.Volume);
                            foreach (var met in metrics)
                            {
                                Logger.Log($"Querying {met} from item {pi.Id}, structure {str.Id}...");
                                var val = pi.ExecuteQuery(met, str);
                                Logger.Log($"Storing value {met} = {val} for item {pi.Id}, structure {str.Id}...");
                                rowItems.Add(val);
                            }
                            if (_doIncludeDVH)
                            {
                                Logger.Log($"Recording DVH from item {pi.Id}, structure {str.Id}...");
                                rowItems.Add(string.Empty); //cell space
                                var dvh     = pi.GetDVHCumulativeData(str, _dvhParams.DosePresentation, _dvhParams.VolumePresentation, _dvhParams.BinWidth);
                                var maxDose = dvh.MaxDose.Dose;
                                for (int i = 0; i < Math.Ceiling(maxDose) + 3; i++)
                                {
                                    var val = dvh.CurveData.GetVolumeAtDose(new VMS.TPS.Common.Model.Types.DoseValue(i, _dvhParams.DoseUnits));
                                    rowItems.Add(val);
                                }
                            }
                            csv.AddRow(rowItems.ToArray());
                        }
                    }

                    Logger.Log($"Closing patient {id}");
                    app.ClosePatient();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    app.ClosePatient();
                }
            }
            return(csv);
        }
Esempio n. 3
0
    /// <summary>
    /// 反序列化.
    /// </summary>
    public static CsvFile Deserialize(MemoryStream stream)
    {
        int ver = FileMgr.ReadInt(stream);

        if (ver != CsvFileMgr.Version)
        {
            NIDebug.Log("Csv版本 {0} 错误, 最新版本 {1}", ver, CsvFileMgr.Version);
            return(null);
        }

        // 文件名
        string name = FileMgr.ReadString(stream);

        CsvFile csv = new CsvFile(name);

        csv.primaryKey = FileMgr.ReadString(stream);

        // 主key类型
        var pkeyType = (LPC.LPCValue.ValueType)FileMgr.ReadInt(stream);

        // 列名
        int n = FileMgr.ReadInt(stream);

        csv.columns = new Dictionary <string, int>(n);
        for (int i = 0; i < n; i++)
        {
            string k = FileMgr.ReadString(stream);
            int    v = FileMgr.ReadInt(stream);
            csv.columns.Add(k, v);
        }

        // 行数
        n        = FileMgr.ReadInt(stream);
        csv.rows = new CsvRow[n];

        // 主key的列
        int pkeyIdx = csv.columns[csv.primaryKey];

        // 每行主key
        for (var i = 0; i < n; i++)
        {
            var row = new CsvRow(csv);
            if (pkeyType == LPCValue.ValueType.INT)
            {
                int pkey = FileMgr.ReadInt(stream);
                row.Add(pkeyIdx, LPCValue.Create(pkey));
            }
            else
            {
                string pkey = FileMgr.ReadString(stream);
                row.Add(pkeyIdx, LPCValue.Create(pkey));
            }
            csv.AddRow(i, row);
        }

        // 行数据
        for (int i = 0; i < n; i++)
        {
            int len = FileMgr.ReadInt(stream);
            csv.rows[i].rowData = new byte[len];
            stream.Read(csv.rows[i].rowData, 0, len);
        }

        return(csv);
    }