コード例 #1
0
 private void AddOnScreenText(Bitmap bmp, ModelConfig modelConfig, string instructions = null)
 {
     using (Graphics g = Graphics.FromImage(bmp))
     {
         g.DrawString(modelConfig.InfoLine1, s_SmallFont, Brushes.LightGray, 0, 5);
         g.DrawString(modelConfig.InfoLine2, s_SmallFont, Brushes.LightGray, 0, 17);
         if (modelConfig.InfoLine3 != null) g.DrawString(modelConfig.InfoLine3, s_SmallFont, Brushes.LightGray, 0, 29);
         if (modelConfig.InfoLine4 != null) g.DrawString(modelConfig.InfoLine4, s_SmallFont, Brushes.LightGray, 0, 41);
         if (instructions != null) g.DrawString(instructions, s_SmallFont, Brushes.LightGray, 0, 100);
         g.Save();
     }
 }
コード例 #2
0
        /// <summary>初始化界面</summary>
        /// <param name="xconfig"></param>
        /// <returns></returns>
        public static FrmItems Create(ModelConfig xconfig)
        {
            FrmItems item = new FrmItems();

            if (xconfig == null) throw new Exception("配置信息异常");

            item.XConfig = xconfig;

            if (xconfig.Items == null) item.CreatDic();
            else
                item.Dic = xconfig.Items;

            return item;
        }
コード例 #3
0
 /// <inheritdoc />
 /// <param name="config"></param>
 protected override void LoadModel(ModelConfig config)
 {
     base.LoadModel(config);
     // Warm up the model after reloading parameters.
     WarmUp();
 }
コード例 #4
0
        private float ModelStarAmplitude(IStar star, float starMag, ModelConfig modelConfig, int bitPix, uint maxSignalValue)
        {
            if (Math.Abs(modelConfig.BVSlope) > 0.001)
            {
                UCAC4Entry ucac4Star = star as UCAC4Entry;
                if (ucac4Star != null)
                {
                    double bv = ucac4Star.MagB - ucac4Star.MagV;
                    if (double.IsNaN(bv)) bv = 0.5; // Default value

                    starMag += (float)(modelConfig.BVSlope * bv);
                }
            }

            if (modelConfig.PSFMagnitudeModelling)
                return (float)((double)(modelConfig.MaxPixelValue - (modelConfig.NoiseMean + modelConfig.DarkFrameMean) * modelConfig.Integration) / Math.Pow(10, (starMag - modelConfig.BrighestUnsaturatedStarMag) / 2.5));
            else
            {
                InitStarAmplitudeModelling(modelConfig, 0.02f, bitPix, maxSignalValue);
                double starMagPeak = ModelStarAmplitudePeak(modelConfig, starMag);
                return (float)starMagPeak;
            }
        }
コード例 #5
0
 private void SaveDarkFrame(ModelConfig modelConfig, float[,] averagedFrame)
 {
     string fileName = null;
     if (m_VideoController.ShowSaveFileDialog(
         "Save Simulated Dark fame",
         "FITS Image (*.fit)|*.fit",
         ref fileName, this) == DialogResult.OK)
     {
         MakeDarkFlatOperation.SaveDarkOrFlatFrame(fileName, modelConfig.FrameWidth, modelConfig.FrameHeight, string.Format("Simulated dark frame from Mean {0} +/- 1", modelConfig.DarkFrameMean), averagedFrame, 0, modelConfig.TotalFrames);
     }
 }
コード例 #6
0
ファイル: Startup.cs プロジェクト: GonTony/MyWebApi
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("ConfigApp.json")
                         .AddEnvironmentVariables()
                         .Build();

            //services.AddSingleton<IConfigurationRoot>(config);
            // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            #region AutoMapper
            services.AddAutoMapper(typeof(Startup));
            #endregion

            #region Swagger
            string CurrBasePath     = AppContext.BaseDirectory;
            string xmlInterfacePath = Path.Combine(CurrBasePath, "TestWebApi.xml");
            string xmlModelPath     = Path.Combine(CurrBasePath, "Test.Core.Model.xml");
            string xmlTPluginPath   = Path.Combine(CurrBasePath, "TPlugin.xml");
            services.AddSwaggerGen(c =>
            {
                typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version.ToString(), new OpenApiInfo
                    {
                        Version     = version.ToString(),
                        Title       = "MyWebApi",
                        Description = $"{version.ToString()}接口说明",
                        //TermsOfService=Uri.
                        Contact = new OpenApiContact {
                            Name = "api"
                        }
                    });
                });
                //c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                //{
                //    Version="v0.1.0",
                //    Title="MyWebApi",
                //    Description="接口说明",
                //    //TermsOfService=Uri
                //    Contact=new Microsoft.OpenApi.Models.OpenApiContact { Name="MyWebApi",Email="xxxx"}
                //});


                c.IncludeXmlComments(xmlInterfacePath, true);//true 为显示controller的注释
                c.IncludeXmlComments(xmlTPluginPath, true);
                c.IncludeXmlComments(xmlModelPath, true);

                //权限 Token
                // var security = new Dictionary<string, IEnumerable<string>> { { "TestWebApi", new string[] { } } };
                //OpenApiSecurityRequirement keys = new OpenApiSecurityRequirement();
                //OpenApiSecurityScheme scheme = new OpenApiSecurityScheme();
                //scheme.Name = "TestWebApi";
                //keys.Add(scheme, new List<string>());
                //c.AddSecurityRequirement(keys);
                //c.OperationFilter<SwaggerHeader>();
                //c.OperationFilter<AddResponseHeardersFilter>();
                c.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
                {
                    Description  = @"JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格",
                    Name         = "Authorization",                                   //jwt默认的参数名称
                    In           = Microsoft.OpenApi.Models.ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
                    Type         = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    Scheme       = "bearer",
                    BearerFormat = "JWT"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
            });
            #endregion

            #region auth认证
            //var configAppsetting= AuthHelper.AppSetting.app(new string[] { "Audience", "Secret" });
            string secretkey  = AuthHelper.AppSetting.app(new string[] { "Audience", "Secret" });
            var    base64Key  = Encoding.UTF8.GetBytes(secretkey);
            var    signingKey = new SymmetricSecurityKey(base64Key);
            services.AddAuthentication(c =>
            {
                c.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                c.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = signingKey,
                    ValidateIssuer           = true,
                    ValidIssuer           = AuthHelper.AppSetting.app(new string[] { "Audience", "Issuer" }),   //发行人
                    ValidateAudience      = true,
                    ValidAudience         = AuthHelper.AppSetting.app(new string[] { "Audience", "Audience" }), //订阅人
                    ValidateLifetime      = true,
                    ClockSkew             = TimeSpan.Zero,                                                      //这个是缓冲过期时间,也就是说,即使我们配置了过期时间,这里也要考虑进去,过期时间+缓冲,默认好像是7分钟,你可以直接设置为0
                    RequireExpirationTime = true,
                };
            });
            #endregion

            services.AddAuthorization(o => {
                o.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                o.AddPolicy("AdminOrTest", policy => policy.RequireRole("Admin", "Test"));
                o.AddPolicy("AdminAndTest", policy => policy.RequireRole("Admin").RequireRole("Test"));
            });

            services.AddScoped <ICaching, MeMoryCache>();

            ModelConfig configModel = new ModelConfig();
            config.Bind(configModel);
            services.AddSingleton(configModel);
            //services.AddSingleton<IRedisManager, RedisManager>();
            AppContextWebApi = new AppContextWA(services);
            //AppContextWebApi.DBConString = configModel.DBConnectionString;
            AppContextWebApi.PluginFactory = new DefaultPluginFactory();
            string pluginPath = Path.Combine(AppContext.BaseDirectory, @"Plugin\netstandard2.0");
            AppContextWebApi.PluginFactory.Load(pluginPath);//加载插件
            AppContextWebApi.PluginFactory.Init(AppContextWebApi);

            #region 将其他程序集中的控制器加入ApplicationPartManager
            var apppart = services.FirstOrDefault(x => x.ServiceType == typeof(ApplicationPartManager))?.ImplementationInstance;
            if (apppart != null)
            {
                ApplicationPartManager apm = apppart as ApplicationPartManager;
                //所有附件程序集
                //AppContextWA ac = AppContextBase.Current as AppContextWA;
                AppContextWebApi.PluginFactory.LoaderAssembly.ForEach((a) =>
                {
                    apm.ApplicationParts.Add(new AssemblyPart(a));
                });
            }
            #endregion

            #region 跨域
            services.AddCors();
            #endregion

            var builder = new ContainerBuilder();
            services.AddSingleton <IRedisManager, RedisManager>();
            builder.RegisterType <TestLogAOP>();
            builder.RegisterType <TestCacheAOP>();
            string basePath        = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
            string assemblyPath    = Path.Combine(basePath, "Test.Core.Service.dll");
            var    assemblyService = Assembly.LoadFile(assemblyPath);
            //var assemblyService = Assembly.Load("Test.Core.Server");
            builder.RegisterAssemblyTypes(assemblyService)
            .AsImplementedInterfaces()                                                          //指定已扫描程序集中的类型注册为提供所有其实现的接口。
            .InstancePerLifetimeScope()
            .EnableInterfaceInterceptors()                                                      //对目标类型启用接口拦截。拦截器将被确定,通过在类或接口上截取属性, 或添加
            .InterceptedBy(typeof(TestLogAOP));                                                 //替换并指定拦截器
            string repositoryAssemblyPath = Path.Combine(basePath, "Test.Core.Repository.dll"); //加载Test.Core.Repository.dll,Test.Core.Service.dll 是为了层级解耦 不解耦的话可直接对以上两个程序集添加引用
            //var assemblyRepoistory = Assembly.Load("Test.Core.Repository");
            var assemblyRepoistory = Assembly.LoadFile(repositoryAssemblyPath);
            builder.RegisterAssemblyTypes(assemblyRepoistory)
            .AsImplementedInterfaces()     //指定已扫描程序集中的类型注册为提供所有其实现的接口。
            .InstancePerLifetimeScope()    //?
            .EnableInterfaceInterceptors() //指明在接口处拦截
            .InterceptedBy(typeof(TestCacheAOP));
            //builder.RegisterType<RedisManager>().As<IRedisManager>().InstancePerLifetimeScope();//等效为 services.AddTransient<IRedisManager, RedisManager>();   InstancePerLifetimeScope:同一个Lifetime生成的对象是同一个实例
            //builder.RegisterType<RedisManager>().As<IRedisManager>().SingleInstance();//等效为 services.AddSingleton<IRedisManager, RedisManager>();
            //builder.RegisterType<RedisManager>().As<IRedisManager>(); //等效为 services.AddScoped<IRedisManager, RedisManager>();
            builder.Populate(services);
            var applicationContainer = builder.Build();


            //services.AddToolDefined();
            return(new AutofacServiceProvider(applicationContainer));
        }
コード例 #7
0
        private void InitStarAmplitudeModelling(ModelConfig modelConfig, float accuracy, int bitPix, uint maxSignalValue)
        {
            if (m_MagnitudeToPeakDict != null)
                return;

            m_MagnitudeToPeakDict = new Dictionary<double, int>();
            m_MagnitudeToPeakMags = new List<double>();
            m_MagnitudeToPeakPeaks = new List<int>();

            var mea = new MeasurementsHelper(
                bitPix,
                TangraConfig.BackgroundMethod.BackgroundMedian,
                TangraConfig.Settings.Photometry.SubPixelSquareSize,
                TangraConfig.Settings.Photometry.Saturation.GetSaturationForBpp(bitPix, maxSignalValue));

            float apertureSize = APERTURE;
            float annulusInnerRadius = (GAP + APERTURE) / APERTURE;
            int annulusMinPixels = (int)(Math.PI * (Math.Pow(ANNULUS + GAP + APERTURE, 2) - Math.Pow(GAP + APERTURE, 2)));

            mea.SetCoreProperties(annulusInnerRadius, annulusMinPixels, CorePhotometrySettings.Default.RejectionBackgroundPixelsStdDev, 2 /* TODO: This must be configurable */);

            int peak = (int)(maxSignalValue - (modelConfig.NoiseMean + modelConfig.DarkFrameMean) * modelConfig.Integration);
            int TOTAL_STEPS = 100;
            double step = Math.Log10(peak) / TOTAL_STEPS;
            double zeroMag = double.NaN;
            for (int ii = 0; ii < TOTAL_STEPS; ii++)
            {
                int amplitude = (int)Math.Round(Math.Pow(10, Math.Log10(peak) - ii * step));
                Pixelmap pixmap = new Pixelmap(64, 64, bitPix, new uint[64 * 64], null, null);
                VideoModelUtils.GenerateStar(pixmap, 32, 32, (float)modelConfig.FWHM, amplitude, 0 /* Gaussian */);
                PSFFit fit = new PSFFit(32, 32);
                AstroImage img = new AstroImage(pixmap);
                uint[,] data = img.GetMeasurableAreaPixels(32, 32, 17);
                uint[,] backgroundPixels = img.GetMeasurableAreaPixels(32, 32, 35);

                fit.Fit(data);

                var result = mea.MeasureObject(new ImagePixel(32, 32), data, backgroundPixels, pixmap.BitPixCamera,
                    TangraConfig.PreProcessingFilter.NoFilter,
                    TangraConfig.PhotometryReductionMethod.AperturePhotometry, TangraConfig.PsfQuadrature.NumericalInAperture,
                    TangraConfig.PsfFittingMethod.DirectNonLinearFit,
                    apertureSize, modelConfig.FWHM, (float)modelConfig.FWHM,
                    new FakeIMeasuredObject(fit),
                    null, null,
                    false);

                if (result == NotMeasuredReasons.TrackedSuccessfully && !mea.HasSaturatedPixels)
                {
                    // Add value for fitting
                    double measurement = mea.TotalReading - mea.TotalBackground;
                    if (double.IsNaN(zeroMag))
                        zeroMag = modelConfig.BrighestUnsaturatedStarMag + 2.5 * Math.Log10(measurement);
                    double magnitude = -2.5 * Math.Log10(measurement) + zeroMag;

                    m_MagnitudeToPeakDict[magnitude] = amplitude;
                    m_MagnitudeToPeakMags.Add(magnitude);
                    m_MagnitudeToPeakPeaks.Add(amplitude);
                }
            }
        }
コード例 #8
0
 public Functional from_config(ModelConfig config)
 => Functional.from_config(config);
コード例 #9
0
ファイル: Global.asax.cs プロジェクト: stulife/ServiceStack
            public override void Configure(Container container)
            {
                IocShared.Configure(this);

                JsConfig.EmitCamelCaseNames = true;

                this.PreRequestFilters.Add((req, res) =>
                {
                    req.Items["_DataSetAtPreRequestFilters"] = true;
                });

                this.GlobalRequestFilters.Add((req, res, dto) =>
                {
                    req.Items["_DataSetAtRequestFilters"] = true;

                    var requestFilter = dto as RequestFilter;
                    if (requestFilter != null)
                    {
                        res.StatusCode = requestFilter.StatusCode;
                        if (!requestFilter.HeaderName.IsNullOrEmpty())
                        {
                            res.AddHeader(requestFilter.HeaderName, requestFilter.HeaderValue);
                        }
                        res.Close();
                    }

                    var secureRequests = dto as IRequiresSession;
                    if (secureRequests != null)
                    {
                        res.ReturnAuthRequired();
                    }
                });

                this.Container.Register <IDbConnectionFactory>(c =>
                                                               new OrmLiteConnectionFactory(
                                                                   "~/App_Data/db.sqlite".MapHostAbsolutePath(),
                                                                   SqliteDialect.Provider)
                {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

                this.Container.Register <ICacheClient>(new MemoryCacheClient());
                //this.Container.Register<ICacheClient>(new BasicRedisClientManager());

                ConfigureAuth(container);

                //this.Container.Register<ISessionFactory>(
                //    c => new SessionFactory(c.Resolve<ICacheClient>()));

                var dbFactory = this.Container.Resolve <IDbConnectionFactory>();

                using (var db = dbFactory.Open())
                    db.DropAndCreateTable <Movie>();

                ModelConfig <Movie> .Id(x => x.Title);

                Routes
                .Add <Movies>("/custom-movies", "GET, OPTIONS")
                .Add <Movies>("/custom-movies/genres/{Genre}")
                .Add <Movie>("/custom-movies", "POST,PUT")
                .Add <Movie>("/custom-movies/{Id}")
                .Add <MqHostStats>("/mqstats");


                var resetMovies = this.Container.Resolve <ResetMoviesService>();

                resetMovies.Post(null);

                container.Register <IRedisClientsManager>(c => new RedisManagerPool());

                Plugins.Add(new ValidationFeature());
                Plugins.Add(new SessionFeature());
                Plugins.Add(new ProtoBufFormat());
                Plugins.Add(new RequestLogsFeature
                {
                    //RequestLogger = new RedisRequestLogger(container.Resolve<IRedisClientsManager>())
                    RequestLogger = new CsvRequestLogger(),
                });
                Plugins.Add(new SwaggerFeature
                {
                    //UseBootstrapTheme = true
                    OperationFilter = x => x.Consumes = x.Produces = new[] { MimeTypes.Json, MimeTypes.Xml }.ToList(),
                    RouteSummary    =
                    {
                        { "/swaggerexamples", "Swagger Examples Summary" }
                    }
                });
                Plugins.Add(new PostmanFeature());
                Plugins.Add(new CorsFeature());
                Plugins.Add(new AutoQueryFeature {
                    MaxLimit = 100
                });
                Plugins.Add(new AdminFeature());

                container.RegisterValidators(typeof(CustomersValidator).Assembly);

                typeof(ResponseStatus)
                .AddAttributes(new ServiceStack.DataAnnotations.DescriptionAttribute("This is the Response Status!"));

                typeof(ResponseStatus)
                .GetProperty("Message")
                .AddAttributes(new ServiceStack.DataAnnotations.DescriptionAttribute("A human friendly error message"));

                //var onlyEnableFeatures = Feature.All.Remove(Feature.Jsv | Feature.Soap);
                SetConfig(new HostConfig
                {
                    AdminAuthSecret = AuthTestsBase.AuthSecret,
                    ApiVersion      = "0.2.0",
                    //EnableFeatures = onlyEnableFeatures,
                    DebugMode = true, //Show StackTraces for easier debugging
                });

                if (StartMqHost)
                {
                    var redisManager = new BasicRedisClientManager();
                    var mqHost       = new RedisMqServer(redisManager);
                    mqHost.RegisterHandler <Reverse>(ExecuteMessage);
                    mqHost.Start();
                    this.Container.Register((IMessageService)mqHost);
                }
            }
コード例 #10
0
ファイル: Generator.cs プロジェクト: landunin/meta-core
        private ModelConfig GenerateModelConfig(
            string outputDirectory,
            CyPhy.TestBench testBench,
            List <string> includeLibs)
        {
            Modelica.SolverSettings solver = new Modelica.SolverSettings(testBench.Children.SolverSettingsCollection.FirstOrDefault());

            ModelConfig modelConfig = new ModelConfig()
            {
                model_name              = "CyPhy.TestBenches." + testBench.Name,
                result_file             = testBench.Name,
                model_file_name         = "package.mo",
                verification_model_name = "CyPhy.TestBenches.verif_" + testBench.Name
            };

            if (solver != null)
            {
                modelConfig.experiment.StartTime = solver.StartTime.ToString();
                modelConfig.experiment.StopTime  = solver.StopTime.ToString();

                if (solver.Tolerance > 0)
                {
                    modelConfig.experiment.Tolerance = solver.Tolerance.ToString();
                }

                if (solver.UsesNumberOfIntervals)
                {
                    modelConfig.experiment.IntervalMethod = "NumberOfIntervals";
                    if (solver.NumberOfIntervals > 0)
                    {
                        modelConfig.experiment.NumberOfIntervals = solver.NumberOfIntervals.ToString();
                    }
                }
                else
                {
                    modelConfig.experiment.IntervalMethod = "Interval";
                    modelConfig.experiment.Interval       = solver.IntervalLength.ToString();
                }

                modelConfig.experiment.Algorithm.Dymola       = solver.DymolaSolver;
                modelConfig.experiment.Algorithm.OpenModelica = solver.OpenModelicaSolver;
                modelConfig.experiment.Algorithm.JModelica    = solver.JModelicaSolver;
                modelConfig.experiment.ToolSelection          = solver.ToolSelection;
            }

            modelConfig.lib_package_paths.Add("../Libraries");
            modelConfig.MSL_version = "3.2";
            foreach (var libPath in includeLibs)
            {
                var library = ModelicaLibrary.GetLibraryFromPath(libPath);
                if (library.Name == "Modelica")
                {
                    modelConfig.MSL_version = library.Version;
                }
                else
                {
                    modelConfig.lib_package_names.Add(library.Name);
                }
            }

            var model_config_filename = Path.Combine(outputDirectory, "model_config.json");

            using (StreamWriter writer = new StreamWriter(model_config_filename))
            {
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(
                    modelConfig,
                    Newtonsoft.Json.Formatting.Indented);

                writer.WriteLine(jsonString);
            }

            return(modelConfig);
        }
コード例 #11
0
ファイル: Generator.cs プロジェクト: landunin/meta-core
        public bool Generate(string originalDesignName)
        {
            var testBench = CyPhyClasses.TestBench.Cast(this.mainParameters.CurrentFCO);

            // generate new manifest file
            AVM.DDP.MetaTBManifest manifest = new AVM.DDP.MetaTBManifest();
            manifest.MakeManifest(testBench, this.mainParameters.OutputDirectory);
            if (string.IsNullOrWhiteSpace(originalDesignName) == false)
            {
                manifest.DesignName = originalDesignName;
            }
            else
            {
                this.Logger.WriteWarning("Could not find an original design. Manifest file will use the name of the test-bench, i.e. '{0}'.", testBench.Name);
            }

            manifest.Serialize(this.mainParameters.OutputDirectory);
            // create scripts directory
            string scriptDir = Path.Combine(this.mainParameters.OutputDirectory, "scripts");

            Directory.CreateDirectory(scriptDir);

            // create modelica libraries directory
            string modelicaDir = Path.Combine(this.mainParameters.OutputDirectory, "Libraries");

            Directory.CreateDirectory(modelicaDir);

            // get CyPhy directory
            string cyphyDir = Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage);

            // copy libraries into the output directory
            var settings = this.mainParameters.config as CyPhy2Modelica_v2Settings;

            foreach (var library in settings.IncludeDirectoryPath)
            {
                var sourcePath = library;
                if (Path.GetFileName(library) == "package.mo")
                {
                    sourcePath = Path.GetDirectoryName(library);
                }

                if (Path.IsPathRooted(sourcePath) == false)
                {
                    // Relative paths are defined relative to the project!
                    sourcePath = Path.Combine(this.mainParameters.ProjectDirectory, sourcePath);
                }

                // TODO: Move this to the Checker
                if ((File.Exists(sourcePath) || Directory.Exists(sourcePath)) == false)
                {
                    this.Logger.WriteError("External Modelica Library does not exist at {0}.", sourcePath);
                    continue;
                }

                var destinationPath = Path.Combine(modelicaDir, Path.GetFileName(sourcePath));
                if (sourcePath.EndsWith(".mo") == false)
                {
                    Directory.CreateDirectory(destinationPath);
                    // Create all of the directories
                    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
                    {
                        if (dirPath.Split(Path.DirectorySeparatorChar)
                            .Where(dir => dir == ".svn" || dir == ".git").Count() > 0)
                        {
                            continue;
                        }

                        Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));
                    }

                    // Copy all the files
                    foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
                    {
                        if (newPath.Split(Path.DirectorySeparatorChar)
                            .Where(dir => dir == ".svn" || dir == ".git").Count() > 0)
                        {
                            continue;
                        }

                        File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true);
                    }
                }
                else
                {
                    File.Copy(sourcePath, destinationPath, true);
                }

                this.Logger.WriteDebug("Copied library from {0} to {1}", sourcePath, destinationPath);
            }

            Templates.open_package_in_dymola dymola_open = new Templates.open_package_in_dymola();
            File.WriteAllText(Path.Combine(this.mainParameters.OutputDirectory, "open_in_dymola.cmd"), dymola_open.TransformText());

            Templates.open_package_in_om om_open = new Templates.open_package_in_om();
            File.WriteAllText(Path.Combine(this.mainParameters.OutputDirectory, "open_in_om.cmd"), om_open.TransformText());


            // generate scripts
            File.WriteAllText(Path.Combine(this.mainParameters.OutputDirectory, "simulate_dymola.cmd"),
                              CyPhy2Modelica_v2.Properties.Resources._simulate_cmd.Replace("TOOL_TO_BE_REPLACED", "Dymola"));

            File.WriteAllText(Path.Combine(this.mainParameters.OutputDirectory, "simulate_om.cmd"),
                              CyPhy2Modelica_v2.Properties.Resources._simulate_cmd.Replace("TOOL_TO_BE_REPLACED", "OpenModelica"));

            File.WriteAllText(Path.Combine(this.mainParameters.OutputDirectory, "simulate_jmodelica.cmd"),
                              CyPhy2Modelica_v2.Properties.Resources._simulate_cmd.Replace("TOOL_TO_BE_REPLACED", "JModelica"));

            var solver = new Modelica.SolverSettings(testBench.Children.SolverSettingsCollection.FirstOrDefault());

            if (solver.ToolSelection.Contains("OpenModelica"))
            {
                this.RunCommand = "simulate_om.cmd";
            }
            else if (solver.ToolSelection.Contains("Dymola"))
            {
                this.RunCommand = "simulate_dymola.cmd";
            }
            else if (solver.ToolSelection.Contains("JModelica"))
            {
                this.RunCommand = "simulate_jmodelica.cmd";

                Templates.jmodelica_compile_py jmodelica_compile = new Templates.jmodelica_compile_py();
                File.WriteAllText(Path.Combine(scriptDir, "jmodelica_compile.py"), jmodelica_compile.TransformText());

                Templates.jmodelica_simulate_py jmodelica_simulate = new Templates.jmodelica_simulate_py();
                File.WriteAllText(Path.Combine(scriptDir, "jmodelica_simulate.py"), jmodelica_simulate.TransformText());
            }
            else
            {
                throw new NotSupportedException(solver.ToolSelection);
            }

            Templates.simulate_py simulate_py = new Templates.simulate_py();
            File.WriteAllText(Path.Combine(scriptDir, "simulate.py"), simulate_py.TransformText());

            //Templates.compile_and_run_jmodelica_py run_jmodelica = new Templates.compile_and_run_jmodelica_py();
            //File.WriteAllText(Path.Combine(scriptDir, "compile_and_run_jmodelica.py"), run_jmodelica.TransformText());

            this.CurrentModelConfig = this.GenerateModelConfig(Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage), testBench, settings.IncludeDirectoryPath);

            this.CopyOverPostProcessingScripts(Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage), testBench);

            this.LimitChecks(Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage), this.CurrentModelConfig.result_file);

            return(true);
        }
コード例 #12
0
ファイル: DatabaseConfig.cs プロジェクト: ackmanFork/Lever
        public void Load(XDocument document)
        {
            XElement eConfiguration = document.Element("configuration");

            if (eConfiguration == null)
            {
                throw new ArgumentException("Invalid configuration element or not found.");
            }

            #region defination
            XElement eDefination = eConfiguration.Element("defination");
            if (eDefination == null)
            {
                throw new ArgumentException("Invalid defination element or not found.");
            }
            else
            {
                this.Defination = new DefinationConfig();

                #region connection
                XElement eConnection = eDefination.Element("connection");
                if (eConnection == null)
                {
                    throw new ArgumentException("Invalid connection element or not found.");
                }
                else
                {
                    this.Defination.Connection = new ConnectionConfig();
                    //// providerName
                    XAttribute aProviderName = eConnection.Attribute("providerName");
                    if (aProviderName == null)
                    {
                        throw new ArgumentException("Invalid providerName attribute or not found.");
                    }
                    else
                    {
                        this.Defination.Connection.ProviderName = aProviderName.Value;
                        if (this.Defination.Connection.ProviderName != "System.Data.SqlClient")
                        {
                            throw new ArgumentException("Only support System.Data.SqlClient sql provider");
                        }
                    }
                    //// connectionString
                    XAttribute aConnectionString = eConnection.Attribute("connectionString");
                    if (aConnectionString == null)
                    {
                        throw new ArgumentException("Invalid connectionString attribute or not found.");
                    }
                    else
                    {
                        this.Defination.Connection.ConnectionString = aConnectionString.Value;
                    }
                }
                #endregion connection

                #region storages
                XElement eStorages = eDefination.Element("storages");
                if (eStorages == null)
                {
                    throw new ArgumentException("Invalid storages element or not found.");
                }
                else
                {
                    this.Defination.Storages = new StoragesConfig();
                    foreach (var name in new string[] { "tables", "views" })
                    {
                        foreach (XElement element in eStorages.Elements(name))
                        {
                            if (element == null)
                            {
                            }
                            else
                            {
                                List <StorageConfig> storages = new List <StorageConfig>();
                                foreach (XElement eItem in element.Elements())
                                {
                                    if (!eItem.Name.LocalName.Equals(OperationAction.Add.ToString(), StringComparison.OrdinalIgnoreCase))
                                    {
                                        throw new ArgumentException("Invalid add element or not found.");
                                    }
                                    else
                                    {
                                        StorageConfig storage = new StorageConfig();
                                        // schema
                                        foreach (XAttribute aItem in eItem.Attributes())
                                        {
                                            switch (aItem.Name.LocalName)
                                            {
                                            case "schema":
                                                storage.Schema = aItem.Value;
                                                break;

                                            case "expression":
                                                storage.Expression = aItem.Value;
                                                break;

                                            default:
                                                throw new ArgumentException("Invalid attribute.");
                                            }
                                        }
                                        storages.Add(storage);
                                    }
                                }

                                switch (name)
                                {
                                case "tables":
                                    this.Defination.Storages.Tables = storages;
                                    break;

                                case "views":
                                    this.Defination.Storages.Views = storages;
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                    }
                }
                #endregion storages

                #region models
                XElement eModels = eDefination.Element("models");
                if (eModels == null)
                {
                }
                else
                {
                    this.Defination.Models = new List <ModelConfig>();
                    foreach (XElement eModel in eModels.Elements("model"))
                    {
                        ModelConfig model = new ModelConfig();
                        foreach (XAttribute aItem in eModel.Attributes())
                        {
                            switch (aItem.Name.LocalName)
                            {
                            case "action":
                                model.Action = (OperationAction)Enum.Parse(typeof(OperationAction), aItem.Value, true);
                                break;

                            case "schema":
                                model.Schema = aItem.Value;
                                break;

                            case "expression":
                                model.Expression = aItem.Value;
                                break;

                            case "description":
                                model.Description = aItem.Value;
                                break;

                            default:
                                throw new ArgumentException("Invalid attribute.");
                            }
                        }

                        XElement eColumns = eModel.Element("columns");
                        if (eColumns == null)
                        {
                        }
                        else
                        {
                            model.Columns = new List <ColumnConfig>();
                            foreach (XElement eColumn in eColumns.Elements("column"))
                            {
                                ColumnConfig column = new ColumnConfig();
                                column.Type = DbType.String;
                                foreach (XAttribute aItem in eColumn.Attributes())
                                {
                                    switch (aItem.Name.LocalName)
                                    {
                                    case "action":
                                        column.Action = (OperationAction)Enum.Parse(typeof(OperationAction), aItem.Value, true);
                                        break;

                                    case "name":
                                        column.Name = aItem.Value;
                                        break;

                                    case "type":
                                        column.Type = (DbType)Enum.Parse(typeof(DbType), aItem.Value, true);
                                        break;

                                    case "length":
                                        column.Length = Convert.ToInt32(aItem.Value);
                                        break;

                                    case "precision":
                                        column.Precision = Convert.ToInt32(aItem.Value);
                                        break;

                                    case "scale":
                                        column.Scale = Convert.ToInt32(aItem.Value);
                                        break;

                                    case "nullable":
                                        column.Nullable = Convert.ToBoolean(aItem.Value);
                                        break;

                                    case "collation":
                                        column.Collation = Convert.ToString(aItem.Value);
                                        break;

                                    case "defaultValue":
                                        column.DefaultValue = Convert.ToString(aItem.Value);
                                        break;

                                    case "description":
                                        column.Description = Convert.ToString(aItem.Value);
                                        break;

                                    default:
                                        throw new ArgumentException("Invalid attribute.");
                                    }
                                }
                                switch (column.Action)
                                {
                                case OperationAction.Add:
                                case OperationAction.Update:
                                case OperationAction.Remove:
                                    break;

                                default:
                                    throw new ArgumentException("Invalid action attribute.");
                                }
                                if (string.IsNullOrEmpty(column.Name))
                                {
                                    throw new ArgumentException("Invalid name attribute.");
                                }

                                model.Columns.Add(column);
                            }
                        }

                        this.Defination.Models.Add(model);
                    }
                }
                #endregion models
            }
            #endregion defination

            #region generation
            XElement eGeneration = eConfiguration.Element("generation");
            if (eGeneration == null)
            {
                throw new ArgumentException("Invalid generation element or not found.");
            }
            else
            {
                Func <XElement, List <string> > GetImports = (element) =>
                {
                    List <string> imports = new List <string>();
                    foreach (XElement eItem in element.Elements())
                    {
                        XAttribute aImport = eItem.Attribute("import");
                        if (aImport == null)
                        {
                            throw new ArgumentException("Invalid import attribute or not found.");
                        }
                        else
                        {
                            switch (eItem.Name.LocalName)
                            {
                            case "add":
                            {
                                imports.Add(aImport.Value);
                            }
                            break;

                            case "remove":
                            {
                                imports.Remove(aImport.Value);
                            }
                            break;
                            }
                        }
                    }
                    return(imports);
                };
                Func <XElement, ClassConfig> GetClassConfig = (element) =>
                {
                    ClassConfig @class = new ClassConfig();
                    foreach (XAttribute aItem in element.Attributes())
                    {
                        switch (aItem.Name.LocalName)
                        {
                        case "namespace":
                            @class.Namespace = aItem.Value;
                            break;

                        case "accessModifier":
                            @class.AccessModifier = (AccessModifier)Enum.Parse(typeof(AccessModifier), aItem.Value, true);
                            break;

                        case "name":
                            @class.Name = aItem.Value;
                            break;

                        case "base":
                            @class.Base = aItem.Value;
                            break;

                        case "useConventionalInterfaces":
                            @class.UseConventionalInterfaces = Convert.ToBoolean(aItem.Value);
                            break;
                        }
                    }
                    return(@class);
                };


                this.Generation = new GenerationConfig();
                XAttribute aEnable = eGeneration.Attribute("enable");
                if (aEnable == null)
                {
                    throw new ArgumentException("Invalid enable attribute or not found.");
                }
                else
                {
                    this.Generation.Enable = Convert.ToBoolean(aEnable.Value);
                }

                XAttribute aMode = eGeneration.Attribute("mode");
                if (aMode == null)
                {
                    throw new ArgumentException("Invalid mode attribute or not found.");
                }
                else
                {
                    this.Generation.Mode = (GenerateMode)Enum.Parse(typeof(GenerateMode), aMode.Value);
                }

                XElement eMain = eGeneration.Element("main");
                if (eMain == null)
                {
                    throw new ArgumentException("Invalid main element or not found.");
                }
                else
                {
                    this.Generation.Main = new MainGenerationConfig();
                    // Imports
                    XElement eImports = eMain.Element("imports");
                    if (eImports == null)
                    {
                    }
                    else
                    {
                        this.Generation.Main.Imports = new List <string>();
                        this.Generation.Main.Imports.AddRange(GetImports(eImports));
                    }
                    // class
                    XElement eClass = eMain.Element("class");
                    if (eClass == null)
                    {
                        throw new ArgumentException("Invalid class element or not found.");
                    }
                    else
                    {
                        this.Generation.Main.Class = GetClassConfig(eClass);
                    }
                }

                XElement eEntity = eGeneration.Element("entity");
                if (eEntity == null)
                {
                    throw new ArgumentException("Invalid entity element or not found.");
                }
                else
                {
                    this.Generation.Entity = new EntityGenerationConfig();
                    // Imports
                    XElement eImports = eEntity.Element("imports");
                    if (eImports == null)
                    {
                    }
                    else
                    {
                        this.Generation.Entity.Imports = new List <string>();
                        this.Generation.Entity.Imports.AddRange(GetImports(eImports));
                    }
                    // class
                    XElement eClass = eEntity.Element("class");
                    if (eClass == null)
                    {
                        throw new ArgumentException("Invalid class element or not found.");
                    }
                    else
                    {
                        this.Generation.Entity.Class = GetClassConfig(eClass);
                    }
                    // DefaultValues
                    XElement eDefaultValues = eEntity.Element("defaultValues");
                    if (eDefaultValues == null)
                    {
                    }
                    else
                    {
                        this.Generation.Entity.DefaultValues = new Dictionary <string, string>();
                        foreach (XElement eItem in eDefaultValues.Elements())
                        {
                            switch (eItem.Name.LocalName)
                            {
                            case "add":
                            {
                                string     type;
                                XAttribute aType = eItem.Attribute("type");
                                if (aType == null)
                                {
                                    throw new ArgumentException("Invalid type attribute or not found.");
                                }
                                else
                                {
                                    type = aType.Value;
                                }
                                string     value;
                                XAttribute aValue = eItem.Attribute("value");
                                if (aValue == null)
                                {
                                    throw new ArgumentException("Invalid value attribute or not found.");
                                }
                                else
                                {
                                    value = aValue.Value;
                                }

                                this.Generation.Entity.DefaultValues.Add(type, value);
                            }
                            break;

                            case "remove":
                            {
                                string     type;
                                XAttribute aType = eItem.Attribute("type");
                                if (aType == null)
                                {
                                    throw new ArgumentException("Invalid type attribute or not found.");
                                }
                                else
                                {
                                    type = aType.Value;
                                }

                                this.Generation.Entity.DefaultValues.Remove(type);
                            }
                            break;

                            default:
                                throw new ArgumentException("Invalid element under defaultValues.");
                            }
                        }
                    }
                }
            }
            #endregion generation
        }
コード例 #13
0
 static RunRequestInfoService()
 {
     //Tell OrmLite what to use for the primary key
     ModelConfig <RequestInfoResponse> .Id(x => x.Host);
 }
コード例 #14
0
 /// <summary>
 /// 仅用于注册页面
 /// </summary>
 public VM_FieldModel(DataTable fielddt, ModelConfig modcfg)
 {
     fieldDT     = fielddt;
     this.config = modcfg;
 }
コード例 #15
0
 public CustomTypeFactory()
 {
     ModelConfig <CustomType> .Id(x => x.CustomId);
 }
コード例 #16
0
ファイル: Global.asax.cs プロジェクト: xamarin/ServiceStack
            public override void Configure(Container container)
            {
                this.RequestFilters.Add((req, res, dto) => {
                    var requestFilter = dto as RequestFilter;
                    if (requestFilter != null)
                    {
                        res.StatusCode = requestFilter.StatusCode;
                        if (!requestFilter.HeaderName.IsNullOrEmpty())
                        {
                            res.AddHeader(requestFilter.HeaderName, requestFilter.HeaderValue);
                        }
                        res.Close();
                    }

                    var secureRequests = dto as IRequiresSession;
                    if (secureRequests != null)
                    {
                        res.ReturnAuthRequired();
                    }
                });

                this.Container.Register <IDbConnectionFactory>(c =>
                                                               new OrmLiteConnectionFactory(
                                                                   "~/App_Data/db.sqlite".MapHostAbsolutePath(),
                                                                   SqliteOrmLiteDialectProvider.Instance)
                {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

                this.Container.Register <ICacheClient>(new MemoryCacheClient());
                //this.Container.Register<ICacheClient>(new BasicRedisClientManager());

                //this.Container.Register<ISessionFactory>(
                //    c => new SessionFactory(c.Resolve<ICacheClient>()));

                var dbFactory = this.Container.Resolve <IDbConnectionFactory>();

                dbFactory.Exec(dbCmd => dbCmd.CreateTable <Movie>(true));
                ModelConfig <Movie> .Id(x => x.Title);

                Routes
                .Add <Movies>("/custom-movies", "GET")
                .Add <Movies>("/custom-movies/genres/{Genre}")
                .Add <Movie>("/custom-movies", "POST,PUT")
                .Add <Movie>("/custom-movies/{Id}")
                .Add <MqHostStats>("/mqstats");

                var resetMovies = this.Container.Resolve <ResetMoviesService>();

                resetMovies.Post(null);

                ValidationFeature.Init(this);
                container.RegisterValidators(typeof(CustomersValidator).Assembly);

                //var onlyEnableFeatures = Feature.All.Remove(Feature.Jsv | Feature.Soap);
                SetConfig(new EndpointHostConfig {
                    //EnableFeatures = onlyEnableFeatures,
                    DebugMode = true,                     //Show StackTraces for easier debugging
                });

                var redisManager = new BasicRedisClientManager();
                var mqHost       = new RedisMqHost(redisManager, 2, null);

                mqHost.RegisterHandler <Reverse>(this.Container.Resolve <ReverseService>().Execute);
                mqHost.Start();

                this.Container.Register((IMessageService)mqHost);
            }
コード例 #17
0
        private void btnGenerateVideo_Click(object sender, EventArgs e)
        {
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                UsageStats.Instance.ModelVideosGenerated++;
                UsageStats.Instance.Save();

                var config = new ModelConfig()
                {
                    FileName = saveFileDialog.FileName,
                    TotalFrames = (int)nudTotalFrames.Value,
                    NoiseMean = (int)nudNoiseMean.Value,
                    NoiseStdDev = (int)nudNoiseStdDev.Value,
                    FlickeringStdDev = (int)nudStarFlickering.Value,
                    StandardStarIntensity = (int)nudStar1Intensity.Value - (int)nudNoiseMean.Value,
                    StandardStarMag = (double)nudStar1Mag.Value,
                    FWHM = (double)nudStar1FWHM.Value,
                    StarMag2 = (double)nudStar2Mag.Value,
                    StarMag3 = (double)nudStar3Mag.Value,
                    StarMag4 = (double)nudStar4Mag.Value,
                    StarMag5 = (double)nudStar5Mag.Value,
                    SimulateStar2 = cbxStar2.Checked,
                    SimulateStar3 = cbxStar3.Checked,
                    SimulateStar4 = cbxStar4.Checked,
                    SimulateStar5 = cbxStar5.Checked,
                    SimulatePassBy = cbClosePassBySim.Checked,
                    PassByDist = (double)nudPassByDist.Value,
                    PassByMag1= (double)nudPassByMag1.Value,
                    PassByMag2 = (double)nudPassByMag2.Value,
                    Gamma = (double)nudGamma.Value,
                    SimulateMovingBackground = cbxPolyBackground.Checked,
                    PolyBgOrder = m_PolyOrder,
                    PolyBgFreq = (int)nudPolyFreq.Value,
                    PolyBgShift = (double)nudPolyShift.Value,
                    PolyBgDepth = m_PolyDepth,
                    OccultedNumberOfFrames = cbOccultationSimulation.Checked ? (int)nudNumOccFrames.Value : 0,
                    MaxDistance = (double)nudMaxDist.Value
                };

                config.InfoLine1 = string.Format("Model Video Generated by Tangra v.{0}", ((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true)[0]).Version);
                config.InfoLine2 = string.Format("Noise: {0} +/- {1}, Flickering: {2}, FWHM: {3}, {4} = {5} mag",
                    config.NoiseMean, config.NoiseStdDev, config.FlickeringStdDev, config.FWHM.ToString("0.0"), config.StandardStarIntensity, config.StandardStarMag.ToString("0.00"));

                var modelConfigStr = new StringBuilder("Stars: ");
                if (config.SimulateStar2) modelConfigStr.AppendFormat("m2={0}; ", config.StarMag2.ToString("0.00"));
                if (config.SimulateStar3) modelConfigStr.AppendFormat("m3={0}; ", config.StarMag3.ToString("0.00"));
                if (config.SimulateStar4) modelConfigStr.AppendFormat("m4={0}; ", config.StarMag4.ToString("0.00"));
                if (config.SimulateStar5) modelConfigStr.AppendFormat("m5={0}; ", config.StarMag5.ToString("0.00"));
                config.InfoLine3 = modelConfigStr.ToString();

                modelConfigStr = new StringBuilder("Pass-By: ");
                if (config.SimulatePassBy) modelConfigStr.AppendFormat("{0}->{1}pix, m'={2}, m\"={3}, {4} occulted frames",
                    config.MaxDistance.ToString("0.0"), config.PassByDist.ToString("0.0"), config.PassByMag1.ToString("0.00"), config.PassByMag2.ToString("0.00"), config.OccultedNumberOfFrames.ToString());
                config.InfoLine4 = modelConfigStr.ToString();

                ThreadPool.QueueUserWorkItem(new WaitCallback(GenerateSimulatedVideo), config);
            }
        }
コード例 #18
0
        public FokkerPlanck(ModelConfig modelConfig,
                            Func <double, double> p_upper, Func <double, double> p_lower)
        {
            m_stepsX = modelConfig.Grid.StepsX;
            m_stepsT = modelConfig.Grid.StepsT;
            m_xMin   = modelConfig.Grid.XMin;
            m_xMax   = modelConfig.Grid.XMax;
            m_tMax   = modelConfig.Grid.TMax;
            m_dx     = modelConfig.Grid.Dx;
            m_dt     = modelConfig.Grid.Dt;

            m_drift     = modelConfig.Model.Drift;
            m_diffusion = modelConfig.Model.Diffusion;

            m_density = new double[m_stepsT][];

            m_t = new double[m_stepsT];

            for (int iTime = 0; iTime < m_stepsT; iTime++)
            {
                m_t[iTime] = iTime * m_dt;
            }

            m_x = new double[m_stepsX];

            for (int iStepX = 0; iStepX < m_stepsX; iStepX++)
            {
                m_x[iStepX] = m_xMin + iStepX * m_dx;
            }

            m_A      = new double[m_stepsT][];
            m_dAdX   = new double[m_stepsT][];
            m_d2AdX2 = new double[m_stepsT][];

            m_B    = new double[m_stepsT][];
            m_dBdx = new double[m_stepsT][];

            m_alpha = new double[m_stepsT][];
            m_beta  = new double[m_stepsT][];
            m_gamma = new double[m_stepsT][];

            m_a = new double[m_stepsT][];
            m_b = new double[m_stepsT][];
            m_c = new double[m_stepsT][];

            for (int iTime = 0; iTime < m_stepsT; iTime++)
            {
                m_density[iTime] = new double[m_stepsX];

                m_A[iTime]      = new double[m_stepsX + 2];
                m_dAdX[iTime]   = new double[m_stepsX];
                m_d2AdX2[iTime] = new double[m_stepsX];

                m_B[iTime]    = new double[m_stepsX + 2];
                m_dBdx[iTime] = new double[m_stepsX];

                m_alpha[iTime] = new double[m_stepsX];
                m_beta[iTime]  = new double[m_stepsX];
                m_gamma[iTime] = new double[m_stepsX];

                m_a[iTime] = new double[m_stepsX];
                m_b[iTime] = new double[m_stepsX];
                m_c[iTime] = new double[m_stepsX];
            }

            for (int iStepX = 0; iStepX < m_stepsX; iStepX++)
            {
                m_density[0][iStepX] = modelConfig.P_0(m_xMin + iStepX * m_dx);
            }

            for (int iTime = 0; iTime < m_stepsT; iTime++)
            {
                m_density[iTime][m_stepsX - 1] = p_upper(iTime * m_dt);
            }

            for (int iTime = 0; iTime < m_stepsT; iTime++)
            {
                m_density[iTime][0] = p_lower(iTime * m_dt);
            }

            for (int iTime = 0; iTime < m_stepsT; iTime++)
            {
                for (int iStepX = 0; iStepX < m_stepsX + 2; iStepX++)
                {
                    m_A[iTime][iStepX] = m_diffusion(new double[] { iTime *m_dt, m_xMin + (iStepX - 1) * m_dx });
                    m_B[iTime][iStepX] = m_drift(new double[] { iTime *m_dt, m_xMin + iStepX *m_dx });
                }
            }
        }
コード例 #19
0
            public override void Configure(Container container)
            {
                JsConfig.EmitCamelCaseNames = true;

                this.PreRequestFilters.Add((req, res) => {
                    req.Items["_DataSetAtPreRequestFilters"] = true;
                });

                this.GlobalRequestFilters.Add((req, res, dto) => {
                    req.Items["_DataSetAtRequestFilters"] = true;

                    var requestFilter = dto as RequestFilter;
                    if (requestFilter != null)
                    {
                        res.StatusCode = requestFilter.StatusCode;
                        if (!requestFilter.HeaderName.IsNullOrEmpty())
                        {
                            res.AddHeader(requestFilter.HeaderName, requestFilter.HeaderValue);
                        }
                        res.Close();
                    }

                    var secureRequests = dto as IRequiresSession;
                    if (secureRequests != null)
                    {
                        res.ReturnAuthRequired();
                    }
                });

                this.Container.Register <IDbConnectionFactory>(c =>
                                                               new OrmLiteConnectionFactory(
                                                                   "~/App_Data/db.sqlite".MapHostAbsolutePath(),
                                                                   SqliteDialect.Provider)
                {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

                this.Container.Register <ICacheClient>(new MemoryCacheClient());
                //this.Container.Register<ICacheClient>(new BasicRedisClientManager());

                ConfigureAuth(container);

                //this.Container.Register<ISessionFactory>(
                //    c => new SessionFactory(c.Resolve<ICacheClient>()));

                var dbFactory = this.Container.Resolve <IDbConnectionFactory>();

                using (var db = dbFactory.Open())
                    db.DropAndCreateTable <Movie>();

                ModelConfig <Movie> .Id(x => x.Title);

                Routes
                .Add <Movies>("/custom-movies", "GET, OPTIONS")
                .Add <Movies>("/custom-movies/genres/{Genre}")
                .Add <Movie>("/custom-movies", "POST,PUT")
                .Add <Movie>("/custom-movies/{Id}")
                .Add <MqHostStats>("/mqstats");


                var resetMovies = this.Container.Resolve <ResetMoviesService>();

                resetMovies.Post(null);

                Plugins.Add(new ValidationFeature());
                Plugins.Add(new SessionFeature());
                Plugins.Add(new ProtoBufFormat());
                Plugins.Add(new SwaggerFeature());
                Plugins.Add(new RequestLogsFeature());

                container.RegisterValidators(typeof(CustomersValidator).Assembly);


                container.Register(c => new FunqSingletonScope()).ReusedWithin(ReuseScope.Default);
                container.Register(c => new FunqRequestScope()).ReusedWithin(ReuseScope.Request);
                container.Register(c => new FunqNoneScope()).ReusedWithin(ReuseScope.None);
                Routes.Add <IocScope>("/iocscope");


                //var onlyEnableFeatures = Feature.All.Remove(Feature.Jsv | Feature.Soap);
                SetConfig(new HostConfig {
                    GlobalResponseHeaders =
                    {
                        { "Access-Control-Allow-Origin",  "*"                               },
                        { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                        { "Access-Control-Allow-Headers", "Content-Type, X-Requested-With"  },
                    },
                    AdminAuthSecret = AuthTestsBase.AuthSecret,
                    //EnableFeatures = onlyEnableFeatures,
                    DebugMode = true, //Show StackTraces for easier debugging
                });

                if (StartMqHost)
                {
                    var redisManager = new BasicRedisClientManager();
                    var mqHost       = new RedisMqServer(redisManager);
                    mqHost.RegisterHandler <Reverse>(ServiceController.ExecuteMessage);
                    mqHost.Start();
                    this.Container.Register((IMessageService)mqHost);
                }
            }
コード例 #20
0
        private void GenerateAAVVideo(ModelConfig modelConfig, List<IStar> stars)
        {
            AavFileCreator.CloseFile();
            AavFileCreator.StartNewFile(modelConfig.FileName, modelConfig.FrameWidth, modelConfig.FrameHeight, modelConfig.Integration);

            m_MagnitudeToPeakDict = null;

            try
            {
                //Pixelmap pixmap = new Pixelmap(modelConfig.FrameWidth, modelConfig.FrameHeight, bitPix, new uint[modelConfig.FrameWidth * modelConfig.FrameHeight], null, null);
                //AddOnScreenText(bmp, modelConfig, "The simulated video stars from the next frame");
                //TangraVideo.AddAviVideoFrame(pixmap, modelConfig.Gamma, null);
                DateTime zeroFrameDT = DateTime.UtcNow;

                uint maxSignalValue = (uint)(255 * modelConfig.Integration);

                Random rndGen = new Random((int)DateTime.Now.Ticks);
                m_SimulatedDarkFrame = new int[modelConfig.FrameWidth, modelConfig.FrameHeight];
                for (int x = 0; x < modelConfig.FrameWidth; x++)
                    for (int y = 0; y < modelConfig.FrameHeight; y++)
                    {
                        if (modelConfig.DarkFrameMean > 0)
                        {
                            double randomPeak = rndGen.Next(0, 100) == 66 ? 255 : 0;
                            double darkPixel = Math.Abs(VideoModelUtils.Random((modelConfig.DarkFrameMean + randomPeak) * modelConfig.Integration, 1));
                            double bgPixel = Math.Min(maxSignalValue, Math.Max(0, darkPixel));
                            m_SimulatedDarkFrame[x, y] = (int)bgPixel;
                        }
                        else
                            m_SimulatedDarkFrame[x, y] = 0;
                    }

                for (int i = 0; i <= modelConfig.TotalFrames; i++)
                {
                    using (Pixelmap pixmap = new Pixelmap(modelConfig.FrameWidth, modelConfig.FrameHeight, 16, new uint[modelConfig.FrameWidth * modelConfig.FrameHeight], null, null))
                    {
                        pixmap.SetMaxSignalValue(maxSignalValue);

                        VideoModelUtils.GenerateNoise(pixmap, m_SimulatedDarkFrame, modelConfig.NoiseMean * modelConfig.Integration, modelConfig.NoiseStdDev * modelConfig.Integration);
                        GenerateFrame(pixmap, stars, modelConfig);

                        DateTime startDT = zeroFrameDT.AddMilliseconds(40 * modelConfig.Integration * i);
                        if (Math.Abs(modelConfig.LinearityCoefficient - 1) > 0.0001)
                        {
                            uint maxVal = pixmap.MaxSignalValue;
                            double gammaCoeff = maxVal / Math.Pow((double)maxVal, modelConfig.LinearityCoefficient);
                            for (int x = 0; x < pixmap.Width; x++)
                            {
                                for (int y = 0; y < pixmap.Height; y++)
                                {
                                    uint nonLinVal = (uint)Math.Round(gammaCoeff * Math.Pow(pixmap[x, y], modelConfig.LinearityCoefficient));
                                    pixmap[x, y] = Math.Min(maxVal, Math.Max(0, nonLinVal));
                                }
                            }
                        }
                        AavFileCreator.AddVideoFrame(startDT, startDT.AddMilliseconds(40 * modelConfig.Integration), pixmap);
                    }

                    InvokeUpdateUI(2, (int)(100.0 * i / modelConfig.TotalFrames), true);
                }
            }
            finally
            {
                AavFileCreator.CloseFile();
            }
        }
コード例 #21
0
        /// <summary>
        /// Builds the config, which consists of the node graph and serialized layers.
        /// </summary>
        ModelConfig get_network_config()
        {
            var config = new ModelConfig
            {
                Name = name
            };

            var node_conversion_map = new Dictionary <string, int>();

            foreach (var layer in _layers)
            {
                var kept_nodes = _should_skip_first_node(layer) ? 1 : 0;
                foreach (var(original_node_index, node) in enumerate(layer.InboundNodes))
                {
                    var node_key = _make_node_key(layer.Name, original_node_index);
                    if (NetworkNodes.Contains(node_key))
                    {
                        node_conversion_map[node_key] = kept_nodes;
                        kept_nodes += 1;
                    }
                }
            }

            var layer_configs = new List <LayerConfig>();

            foreach (var layer in _layers)
            {
                var filtered_inbound_nodes = new List <NodeConfig>();
                foreach (var(original_node_index, node) in enumerate(layer.InboundNodes))
                {
                    var node_key = _make_node_key(layer.Name, original_node_index);
                    if (NetworkNodes.Contains(node_key) && !node.is_input)
                    {
                        var node_data = node.serialize(_make_node_key, node_conversion_map);
                        filtered_inbound_nodes.append(node_data);
                    }
                }

                var layer_config = generic_utils.serialize_keras_object(layer);
                layer_config.Name         = layer.Name;
                layer_config.InboundNodes = filtered_inbound_nodes;
                layer_configs.Add(layer_config);
            }
            config.Layers = layer_configs;

            // Gather info about inputs and outputs.
            var model_inputs = new List <NodeConfig>();

            foreach (var i in range(_input_layers.Count))
            {
                var(layer, node_index, tensor_index) = _input_coordinates[i];
                var node_key = _make_node_key(layer.Name, node_index);
                if (!NetworkNodes.Contains(node_key))
                {
                    continue;
                }
                var new_node_index = node_conversion_map[node_key];
                model_inputs.append(new NodeConfig
                {
                    Name        = layer.Name,
                    NodeIndex   = new_node_index,
                    TensorIndex = tensor_index
                });
            }
            config.InputLayers = model_inputs;

            var model_outputs = new List <NodeConfig>();

            foreach (var i in range(_output_layers.Count))
            {
                var(layer, node_index, tensor_index) = _output_coordinates[i];
                var node_key = _make_node_key(layer.Name, node_index);
                if (!NetworkNodes.Contains(node_key))
                {
                    continue;
                }
                var new_node_index = node_conversion_map[node_key];
                model_outputs.append(new NodeConfig
                {
                    Name        = layer.Name,
                    NodeIndex   = new_node_index,
                    TensorIndex = tensor_index
                });
            }
            config.OutputLayers = model_outputs;

            return(config);
        }
コード例 #22
0
        private void GenerateFrame(Pixelmap pixmap, List<IStar> stars, ModelConfig modelConfig)
        {
            var mea = new MeasurementsHelper(
                pixmap.BitPixCamera,
                TangraConfig.BackgroundMethod.BackgroundMedian,
                TangraConfig.Settings.Photometry.SubPixelSquareSize,
                TangraConfig.Settings.Photometry.Saturation.GetSaturationForBpp(pixmap.BitPixCamera, pixmap.MaxSignalValue));

            float apertureSize = APERTURE;
            float annulusInnerRadius = (GAP + APERTURE) / APERTURE;
            int annulusMinPixels = (int)(Math.PI * (Math.Pow(ANNULUS + GAP + APERTURE, 2) - Math.Pow(GAP + APERTURE, 2)));

            mea.SetCoreProperties(annulusInnerRadius, annulusMinPixels, CorePhotometrySettings.Default.RejectionBackgroundPixelsStdDev, 2 /* TODO: This must be configurable */);

            var measurements = new Dictionary<IStar, double>();

            foreach (IStar star in stars)
            {
                double x, y;

                GetOnPlateCoordinates(star.RADeg, star.DEDeg, modelConfig, out x, out y);

                if (x < 0 || x > modelConfig.FrameWidth || y < 0 || y > modelConfig.FrameHeight)
                    continue;

                float starMag = GetStarMag(star, modelConfig.PhotometricFilter);
                float iMax = ModelStarAmplitude(star, starMag, modelConfig, pixmap.BitPixCamera, pixmap.MaxSignalValue);

                if (!float.IsNaN(iMax))
                {
                    VideoModelUtils.GenerateStar(pixmap, (float)x, (float)y, (float)modelConfig.FWHM, iMax, 0 /*Use Gaussian */);

                    if (modelConfig.CheckMagnitudes)
                    {
                        var image = new AstroImage(pixmap);
                        uint[,] data = image.GetMeasurableAreaPixels((int)x, (int)y, 17);
                        uint[,] backgroundPixels = image.GetMeasurableAreaPixels((int)x, (int)y, 35);

                        PSFFit fit = new PSFFit((int)x, (int)y);
                        fit.Fit(data);

                        var result = mea.MeasureObject(new ImagePixel(x, y), data, backgroundPixels, pixmap.BitPixCamera,
                            TangraConfig.PreProcessingFilter.NoFilter,
                            TangraConfig.PhotometryReductionMethod.AperturePhotometry, TangraConfig.PsfQuadrature.NumericalInAperture,
                            TangraConfig.PsfFittingMethod.DirectNonLinearFit,
                            apertureSize, modelConfig.FWHM, (float)modelConfig.FWHM,
                            new FakeIMeasuredObject(fit),
                            null, null,
                            false);

                        if (result == NotMeasuredReasons.TrackedSuccessfully && !mea.HasSaturatedPixels)
                        {
                            // Add value for fitting
                            measurements.Add(star, mea.TotalReading - mea.TotalBackground);
                        }
                    }
                }
            }

            if (modelConfig.CheckMagnitudes)
                CalculateGagnitudeFit(measurements, modelConfig.BVSlope);
        }
コード例 #23
0
        public static bool ScanFiles(FileTypeEnum type, FileFormatEnum srcFormat, string[] inputPaths, out List <int> newMalwareHistoryIds, out string message)
        {
            message = "";
            bool hasError = false;

            var targetPaths = new List <string>();
            var filesDict   = new Dictionary <string, string>();

            newMalwareHistoryIds = new List <int>();

            try
            {
                var filteredInputPaths = new List <string>();
                foreach (var inputPath in inputPaths)
                {
                    if (!filteredInputPaths.Any(x => x.Equals(inputPath, StringComparison.OrdinalIgnoreCase)))
                    {
                        filteredInputPaths.Add(inputPath);
                    }
                }
                inputPaths = filteredInputPaths.ToArray();

                if (type == FileTypeEnum.FILES)
                {
                    // Convert to graph
                    if (srcFormat != FileFormatEnum.GRAPH)
                    {
                        foreach (var inputPath in inputPaths)
                        {
                            var graphPath = Path.Combine(TEMP_DIR, Guid.NewGuid().ToString("D"));

                            try
                            {
                                if (Home.GetInstance().miningController.Convert(inputPath, string.Empty, srcFormat, graphPath, FileFormatEnum.GRAPH, false))
                                {
                                    targetPaths.Add(graphPath);
                                    filesDict[graphPath] = inputPath;
                                }
                            }
                            catch (Exception ex)
                            {
                                if (File.Exists(graphPath))
                                {
                                    File.Delete(graphPath);
                                }
                            }
                        }
                    }
                    else
                    {
                        targetPaths = inputPaths.ToList();

                        foreach (var path in inputPaths)
                        {
                            filesDict[path] = path;
                        }
                    }
                }
                else
                {
                    targetPaths = inputPaths.ToList();
                }

                // Load settings
                var appSettingsPath = Path.Combine(Home.GetInstance().GetDataLocation(), APP_SETTINGS_FILE_NAME);
                if (!File.Exists(appSettingsPath))
                {
                    throw new Exception("App settings not found");
                }
                AppSettings appSettings = JsonConvert.DeserializeObject <AppSettings>(File.ReadAllText(appSettingsPath));

                if (!File.Exists(appSettings.ConfigPath))
                {
                    throw new Exception("Model config not found");
                }
                ModelConfig modeConfig = JsonConvert.DeserializeObject <ModelConfig>(File.ReadAllText(appSettings.ConfigPath));

                var outputPath = Path.Combine(OUTPUT_DIR, DateTime.Now.ToString("yyMMdd_HHmmss"));

                Environment.SetEnvironmentVariable(MODE_ID_ENV_NAME, ((int)ModeEnum.SCAN).ToString());
                Environment.SetEnvironmentVariable(OUTPUT_DIR_ENV_NAME, outputPath);

                Environment.SetEnvironmentVariable(CLASSIFIER_PATH_ENV_NAME, appSettings.ClassifierPath);
                Environment.SetEnvironmentVariable(SCALER_PATH_ENV_NAME, appSettings.DataScalerPath);
                Environment.SetEnvironmentVariable(DECOMPOSITION_PATH_ENV_NAME, appSettings.DataDecompositionPath);
                Environment.SetEnvironmentVariable(EXTRA_PATH_ENV_NAME, appSettings.ExtraDataPath);

                Environment.SetEnvironmentVariable(TARGET_TYPE_ID_ENV_NAME, ((int)type).ToString());
                Environment.SetEnvironmentVariable(TARGET_PATHS_ENV_NAME, string.Join(";", targetPaths));

                Environment.SetEnvironmentVariable(FEATURE_ID_ENV_NAME, modeConfig.feature_id.ToString());
                Environment.SetEnvironmentVariable(SEQUENCE_LEN_ENV_NAME, modeConfig.sequence_len.ToString());

                var output      = Wrapper.ExecutePythonMain();
                var predictLine = output.Split('\n').Where(line => line.Contains("predicts:")).FirstOrDefault();

                bool[] predicts = new bool[0];
                if (predictLine != null && predictLine.Length > 0)
                {
                    int pred = 0;
                    predicts = predictLine.Split(' ')
                               .Select(part => part.Trim())
                               .Where(part => part.Length > 0 && int.TryParse(part, out pred))
                               .Select(part => int.Parse(part) > 0)
                               .ToArray();
                }

                var filesScanningControler = Home.GetInstance().filesScanningControler;
                var histories = filesScanningControler.LoadHistory();
                int nextId    = 0;
                if (histories.Count > 0)
                {
                    nextId = histories.Max(x => x.Id) + 1;
                }

                for (int iPredict = 0; iPredict < predicts.Length; iPredict++)
                {
                    histories.Add(new FileHistoryRecord(nextId, filesDict[targetPaths[iPredict]], srcFormat, predicts[iPredict], outputPath, iPredict.ToString() + ".png"));
                    if (predicts[iPredict])
                    {
                        newMalwareHistoryIds.Add(nextId);
                    }
                    nextId += 1;
                }
                filesScanningControler.SaveHistory(histories);
                filesScanningControler.BindHitoryToView(histories);

                message  = "SCAN RESULT" + Environment.NewLine;
                message += "Total: " + inputPaths.Length.ToString() + Environment.NewLine;
                message += "Valid:" + predicts.Length.ToString() + Environment.NewLine;
                message += "Detected: " + predicts.Count(x => x).ToString() + Environment.NewLine;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message);
                hasError = true;
            }

            return(!hasError);
        }
コード例 #24
0
        /// <summary>
        /// Sets up the cosmetic data for this model, or, what's displayed in the GUI for the program.<para/>
        /// This specific method populates data that is common across all imported models.
        /// </summary>
        /// <param name="model">The model containing other data, such as the <see cref="Implementation"/>.</param>
        /// <param name="dataTreeParent">This is the instance in the data tree that represents this object in the hierarchy. If null, this method call is skipped.</param>
        /// <param name="dataTreeNameIsImplementation">If <see langword="true"/>, the name of <paramref name="dataTreeParent"/> is the implementation of the model, so the implementation property will not be added.</param>
        public static void SetupCosmeticInformation(ModelConfig model, DataTreeObject dataTreeParent, bool dataTreeNameIsImplementation)
        {
            if (dataTreeParent == null)
            {
                return;
            }
            Implementation impl = model.implementation;

            if (!dataTreeNameIsImplementation)
            {
                // If this is true, the name of the actual node is the implementation, rendering this property useless.

                string implementationName = JavaClassNameStripper.GetWholeClassName(impl.getClass().getName()) ?? "Unknown Implementation";
                dataTreeParent.AddSimpleProperty("Implementation", implementationName.Replace("$", "::"), SilkImage.Config, SilkImage.Config, true);
            }

            // It's imported!
            // ...Unless it's a CompoundConfig. (I mean given the properties below it makes sense, it's just a container, not actual model data.)
            if (impl is Imported imported)
            {
                //RootDataTreeObject.AddSimpleProperty("Scale", model.scale);
                List <object> influences = new List <object>(3);
                if (imported.influences.fog)
                {
                    influences.Add(new DataTreeObjectProperty("Fog", SilkImage.Shading));
                }
                if (imported.influences.lights)
                {
                    influences.Add(new DataTreeObjectProperty("Lights", SilkImage.Light));
                }
                if (imported.influences.projections)
                {
                    influences.Add(new DataTreeObjectProperty("Projections", SilkImage.Texture));
                }
                if (influences.Count > 0)
                {
                    dataTreeParent.AddSimpleProperty("Influenced By...", influences.ToArray(), displaySinglePropertiesInline: false);
                }

                /*
                 * MaterialMapping[] matMaps = imported.materialMappings;
                 * object[] materialProperties = new object[matMaps.Length];
                 * for (int idx = 0; idx < materialProperties.Length; idx++) {
                 *      ConfigReference mtlRef = matMaps[idx].material;
                 *      ConfigReference texCfg = (ConfigReference)mtlRef.getArguments().getOrDefault("Texture", null);
                 *      if (texCfg != null) {
                 *              string texFile = (string)texCfg.getArguments().getOrDefault("File", "?");
                 *              materialProperties[idx] = new DataTreeObjectProperty(texFile, SilkImage.Reference, false);
                 *      } else {
                 *              materialProperties[idx] = matMaps[idx].texture;
                 *      }
                 * }
                 * dataTreeParent.AddSimpleProperty("Textures", materialProperties, SilkImage.Value, SilkImage.Texture, false);
                 */
            }
            List <object> parameters = new List <object>();

            foreach (Parameter prop in model.parameters)
            {
                if (prop is Parameter.Direct direct)
                {
                    DataTreeObject paths = new DataTreeObject {
                        ImageKey = SilkImage.Tag,
                        Text     = "Direct: " + direct.name
                    };
                    int idx = 0;
                    foreach (string path in direct.paths)
                    {
                        paths.AddSimpleProperty("Path " + idx, path);
                        idx++;
                    }
                    parameters.Add(paths);
                }
                else if (prop is Parameter.Choice choice)
                {
                    DataTreeObject choices = new DataTreeObject {
                        ImageKey = SilkImage.Value,
                        Text     = "Choice: " + choice.name + " [Default: " + choice.choice + "]"
                    };
                    List <DataTreeObject> choiceList = new List <DataTreeObject>();
                    foreach (Parameter.Choice.Option option in choice.options)
                    {
                        // choiceList.Add(c);
                        DataTreeObject choiceInfo = new DataTreeObject {
                            ImageKey = SilkImage.Tag,
                            Text     = option.name
                        };
                        ArgumentMap args = option.arguments;
                        object[]    keys = args.keySet().toArray();
                        foreach (object key in keys)
                        {
                            choiceInfo.AddSimpleProperty(key.ToString(), args.get(key));
                        }

                        choiceList.Add(choiceInfo);
                    }
                    choices.AddSimpleProperty("Choices", choiceList.ToArray(), SilkImage.Value, SilkImage.Tag, false);

                    List <DataTreeObject> subDirects = new List <DataTreeObject>();
                    foreach (Parameter.Direct dir in choice.directs)
                    {
                        DataTreeObject dirObj = new DataTreeObject {
                            ImageKey = SilkImage.Tag,
                            Text     = "Direct: " + dir.name
                        };
                        int idx = 0;
                        foreach (string path in dir.paths)
                        {
                            dirObj.AddSimpleProperty("Path " + idx, path);
                            idx++;
                        }
                        subDirects.Add(dirObj);
                    }
                    choices.AddSimpleProperty("Choice Directs", subDirects.ToArray(), SilkImage.Value, SilkImage.Tag, false);
                    parameters.Add(choices);
                }
                else
                {
                    parameters.Add($"{prop.name} [{prop.GetType().FullName}]");
                }
            }
            dataTreeParent.AddSimpleProperty("Parameters", parameters.ToArray(), SilkImage.Value, SilkImage.Tag, false);
        }
コード例 #25
0
        private void GenerateAVIVideo(ModelConfig modelConfig, List<IStar> stars)
        {
            TangraVideo.CloseAviFile();
            TangraVideo.StartNewAviFile(modelConfig.FileName, modelConfig.FrameWidth, modelConfig.FrameHeight, 8, 25, false);

            m_MagnitudeToPeakDict = null;

            try
            {
                //Pixelmap pixmap = new Pixelmap(modelConfig.FrameWidth, modelConfig.FrameHeight, bitPix, new uint[modelConfig.FrameWidth * modelConfig.FrameHeight], null, null);
                //AddOnScreenText(bmp, modelConfig, "The simulated video stars from the next frame");
                //TangraVideo.AddAviVideoFrame(pixmap, modelConfig.Gamma, null);

                uint maxSignalValue = (uint)(255 * modelConfig.Integration);

                Random rndGen = new Random((int)DateTime.Now.Ticks);
                m_SimulatedDarkFrame = new int[modelConfig.FrameWidth, modelConfig.FrameHeight];
                for (int x = 0; x < modelConfig.FrameWidth; x++)
                    for (int y = 0; y < modelConfig.FrameHeight; y++)
                    {
                        if (modelConfig.DarkFrameMean > 0)
                        {
                            double randomPeak = rndGen.Next(0, 100) == 66 ? 255 : 0;
                            double darkPixel = Math.Abs(VideoModelUtils.Random((modelConfig.DarkFrameMean + randomPeak)* modelConfig.Integration, 1));
                            double bgPixel = Math.Min(maxSignalValue, Math.Max(0, darkPixel));
                            m_SimulatedDarkFrame[x, y] = (int)bgPixel;
                        }
                        else
                            m_SimulatedDarkFrame[x, y] = 0;
                    }

                for (int i = 0; i <= modelConfig.TotalFrames; i++)
                {
                    using (Pixelmap pixmap = new Pixelmap(modelConfig.FrameWidth, modelConfig.FrameHeight, 16, new uint[modelConfig.FrameWidth * modelConfig.FrameHeight], null, null))
                    {
                        pixmap.SetMaxSignalValue(maxSignalValue);

                        VideoModelUtils.GenerateNoise(pixmap, m_SimulatedDarkFrame, modelConfig.NoiseMean * modelConfig.Integration, modelConfig.NoiseStdDev * modelConfig.Integration);
                        GenerateFrame(pixmap, stars, modelConfig);

                        TangraVideo.AddAviVideoFrame(pixmap, modelConfig.LinearityCoefficient, (int)pixmap.MaxSignalValue);
                    }

                    InvokeUpdateUI(2, (int)(100.0 * i / modelConfig.TotalFrames), true);
                }
            }
            finally
            {
                TangraVideo.CloseAviFile();
            }
        }
コード例 #26
0
 public RedisManager(ModelConfig config)
 {
     redisConnectionString = config.AppSettings.RedisCaching.ConnectionString;
     redisConnection       = GetRedisConnection();
 }
コード例 #27
0
        private void GetOnPlateCoordinates(double raDeg, double deDeg, ModelConfig modelConfig, out double x, out double y)
        {
            double tangentalX, tangentalY;
            TangentPlane.CelestialToTangent(raDeg, deDeg, modelConfig.RADeg2000, modelConfig.DEDeg2000, out tangentalX, out tangentalY);

            tangentalY = -tangentalY;

            double plateX = tangentalX * (modelConfig.PlateFocLength * 1000.0 / modelConfig.PlatePixWidth);
            double plateY = tangentalY * (modelConfig.PlateFocLength * 1000.0 / modelConfig.PlatePixHeight);

            double mtxX = Math.Cos(modelConfig.PlateRotAngleRadians) * plateX + Math.Sin(modelConfig.PlateRotAngleRadians) * plateY;
            double mtxY = Math.Cos(modelConfig.PlateRotAngleRadians) * plateY - Math.Sin(modelConfig.PlateRotAngleRadians) * plateX;

            x = (modelConfig.FrameWidth / 2) + mtxX * modelConfig.MatrixToImageScaleX;
            y = (modelConfig.FrameHeight / 2) + mtxY * modelConfig.MatrixToImageScaleY;
        }
コード例 #28
0
        public void Can_get_if_HasIdCustomIntProperty()
        {
            ModelConfig <HasIdCustomIntProperty> .Id(x => x.CustomId);

            Assert.That(new HasIdCustomIntProperty().GetId(), Is.EqualTo(IntValue));
        }
コード例 #29
0
 private void InvokeSaveDarkFrame(ModelConfig modelConfig, float[,] averagedFrame)
 {
     try
     {
         Invoke(new SaveDarkFrameDelegate(SaveDarkFrame), new object[] { modelConfig, averagedFrame });
     }
     catch (InvalidOperationException)
     { }
 }
コード例 #30
0
 public void SetConfig()
 {
     ModelConfig modelConfig = ModelConfig.GetInstance();
     //string str
 }
コード例 #31
0
        private double ModelStarAmplitudePeak(ModelConfig modelConfig, double starMag)
        {
            for (int i = 0; i < m_MagnitudeToPeakMags.Count - 1; i++)
            {
                if (m_MagnitudeToPeakMags[i] < starMag && m_MagnitudeToPeakMags[i + 1] > starMag)
                {
                    double interval = Math.Pow(10, m_MagnitudeToPeakMags[i + 1] - m_MagnitudeToPeakMags[i]);

                    return m_MagnitudeToPeakPeaks[i + 1] + Math.Log10(Math.Pow(10, starMag - m_MagnitudeToPeakMags[i]) * interval) * (m_MagnitudeToPeakPeaks[i] - m_MagnitudeToPeakPeaks[i + 1]);
                }
            }

            return double.NaN;
        }
コード例 #32
0
        private Pixelmap GenerateFrame(double percentDone, int frameNo, ModelConfig modelConfig)
        {
            float I1 = (float)modelConfig.StandardStarIntensity;
            float I2 = GetPsfMaxForMagnitude(modelConfig.StandardStarIntensity, modelConfig.StandardStarMag, modelConfig.StarMag2);
            float I3 = GetPsfMaxForMagnitude(modelConfig.StandardStarIntensity, modelConfig.StandardStarMag, modelConfig.StarMag3);
            float I4 = GetPsfMaxForMagnitude(modelConfig.StandardStarIntensity, modelConfig.StandardStarMag, modelConfig.StarMag4);
            float I5 = GetPsfMaxForMagnitude(modelConfig.StandardStarIntensity, modelConfig.StandardStarMag, modelConfig.StarMag5);
            int IPB1 = (int)Math.Round((double)modelConfig.StandardStarIntensity / Math.Pow(10, (modelConfig.PassByMag1 - modelConfig.StandardStarMag) / 2.5));
            int IPB2 = (int)Math.Round((double)modelConfig.StandardStarIntensity / Math.Pow(10, (modelConfig.PassByMag2 - modelConfig.StandardStarMag) / 2.5));
            float fwhm1 = (float) modelConfig.FWHM;
            // NOTE: Use the same FWHM to get accurate photometry
            //float fwhm2 = (float)(modelConfig.FWHM + (modelConfig.StandardStarMag - modelConfig.StarMag2) * FWHM_GAIN_PER_MAG);
            //float fwhm3 = (float)(modelConfig.FWHM + (modelConfig.StandardStarMag - modelConfig.StarMag3) * FWHM_GAIN_PER_MAG);
            //float fwhm4 = (float)(modelConfig.FWHM + (modelConfig.StandardStarMag - modelConfig.StarMag4) * FWHM_GAIN_PER_MAG);
            //float fwhm5 = (float)(modelConfig.FWHM + (modelConfig.StandardStarMag - modelConfig.StarMag5) * FWHM_GAIN_PER_MAG);
            float fwhm_pb1 = (float)(modelConfig.FWHM + (modelConfig.StandardStarMag - modelConfig.PassByMag1) * FWHM_GAIN_PER_MAG);
            float fwhm_pb2 = (float)(modelConfig.FWHM + (modelConfig.StandardStarMag - modelConfig.PassByMag2) * FWHM_GAIN_PER_MAG);

            if (modelConfig.FlickeringStdDev > 0)
            {
                I1 = (int)Math.Round(VideoModelUtils.Random(I1, modelConfig.FlickeringStdDev));
                I2 = (int)Math.Round(VideoModelUtils.Random(I2, modelConfig.FlickeringStdDev));
                I3 = (int)Math.Round(VideoModelUtils.Random(I3, modelConfig.FlickeringStdDev));
                I4 = (int)Math.Round(VideoModelUtils.Random(I4, modelConfig.FlickeringStdDev));
                I5 = (int)Math.Round(VideoModelUtils.Random(I5, modelConfig.FlickeringStdDev));
            }

            int[,] simulatedBackground = new int[300,200];
            for (int x = 0; x < 300; x++)
            for (int y = 0; y < 200; y++)
            {
                simulatedBackground[x, y] = 0;
            }

            using (Bitmap bmp = new Bitmap(300, 200, PixelFormat.Format24bppRgb))
            {

                if (modelConfig.SimulateMovingBackground)
                {
                    simulatedBackground = m_BgModelGen.GenerateBackground(modelConfig.PolyBgOrder, modelConfig.PolyBgFreq, modelConfig.PolyBgShift, modelConfig.TotalFrames * percentDone, 110, 100, 35);
                }

                VideoModelUtils.GenerateNoise(bmp, simulatedBackground, modelConfig.NoiseMean, modelConfig.NoiseStdDev);

                VideoModelUtils.GenerateStar(bmp, 25, 160, (float)fwhm1, I1);
                if (modelConfig.SimulateStar2) VideoModelUtils.GenerateStar(bmp, 75, 160, (float)fwhm1, I2);
                if (modelConfig.SimulateStar3) VideoModelUtils.GenerateStar(bmp, 125, 160, (float)fwhm1, I3);
                if (modelConfig.SimulateStar4) VideoModelUtils.GenerateStar(bmp, 175, 160, (float)fwhm1, I4);
                if (modelConfig.SimulateStar5) VideoModelUtils.GenerateStar(bmp, 225, 160, (float)fwhm1, I5);

                if (modelConfig.SimulatePassBy)
                {
                    double maxVerticaldistance = Math.Sqrt(modelConfig.MaxDistance * modelConfig.MaxDistance - modelConfig.PassByDist * modelConfig.PassByDist);
                    bool isOcculted = false;
                    if (modelConfig.OccultedNumberOfFrames > 0 && Math.Abs(modelConfig.PassByDist) < 0.2)
                    {
                        int firstOccFrame = (modelConfig.TotalFrames / 2) - modelConfig.OccultedNumberOfFrames;
                        int lastOccFrame = (modelConfig.TotalFrames / 2) - 1;
                        isOcculted = frameNo >= firstOccFrame && frameNo <= lastOccFrame;
                    }
                    if (!isOcculted) VideoModelUtils.GenerateStar(bmp, 110, 100, fwhm_pb1, IPB1);

                    VideoModelUtils.GenerateStar(bmp, 110 + (float)modelConfig.PassByDist, (float)(100 - maxVerticaldistance + (2 * maxVerticaldistance) * percentDone), fwhm_pb2, IPB2);
                }

                AddOnScreenText(bmp, modelConfig);

                return Pixelmap.ConstructFromBitmap(bmp, TangraConfig.ColourChannel.Red);
            }
        }
コード例 #33
0
        private void btnGenerateVideo_Click(object sender, EventArgs e)
        {
            if (!ValidateParameters())
                return;

            if (cbxVideoFormat.SelectedIndex == 0)
            {
                saveFileDialog.Filter = "AAV Files (*.aav)|*.aav";
                saveFileDialog.DefaultExt = "aav";
            }
            else if (cbxVideoFormat.SelectedIndex == 1)
            {
                saveFileDialog.Filter = "AVI Files (*.avi)|*.avi";
                saveFileDialog.DefaultExt = "avi";
            }

            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                UsageStats.Instance.ModelVideosGenerated++;
                UsageStats.Instance.Save();

                var config = new ModelConfig()
                {
                    FileName = saveFileDialog.FileName,
                    IsAAVFile = cbxVideoFormat.SelectedIndex == 0,
                    Integration = (int)Math.Pow(2, cbxAAVIntegration.SelectedIndex),
                    TotalFrames = (int)nudTotalFrames.Value,
                    FrameWidth = (int)nudFrameWidth.Value,
                    FrameHeight = (int)nudFrameHeight.Value,
                    NoiseMean = (int)nudNoiseMean.Value,
                    NoiseStdDev = (int)nudNoiseStdDev.Value,
                    FlickeringStdDev = (int)nudStarFlickering.Value,
                    FWHM = (double)nudStar1FWHM.Value,
                    BrighestUnsaturatedStarMag = (double)nudFirstSaturatedMag.Value,
                    LimitStarMag = (double)nudLimitMag.Value,
                    RADeg2000 = m_RA * 15,
                    DEDeg2000 = m_DE,
                    PlatePixWidth = (double)nudPlatePixWidth.Value,
                    PlatePixHeight = (double)nudPlatePixHeight.Value,
                    PlateFocLength = (double)nudPlateFocLength.Value,
                    PhotometricFilter = (ModelledFilter)cbxPhotometricFilter.SelectedIndex,
                    BVSlope = (double)nudBVSlope.Value,
                    LinearityCoefficient = (double)nudNonLinearity.Value,
                    DarkFrameMean = cbxProduceDark.Checked ? (int)nudDarkMean.Value : 0,
                    CheckMagnitudes = cbxCheckMagnitudes.Checked,
                    PSFMagnitudeModelling = cbxPSFStarModelling.Checked
                };

                config.PlateRotAngleRadians = (double)nudPlateRotation.Value * Math.PI / 180.0;
                config.MatrixToImageScaleX = config.FrameWidth / (double)nudMatrixWidth.Value;
                config.MatrixToImageScaleY = config.FrameHeight / (double)nudMatrixHeight.Value;

                config.InfoLine1 = string.Format("Model Video Generated by Tangra v.{0}", ((AssemblyFileVersionAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true)[0]).Version);
                config.InfoLine2 = string.Format("Noise: {0} +/- {1}, Flickering: {2}, FWHM: {3}", config.NoiseMean, config.NoiseStdDev, config.FlickeringStdDev, config.FWHM.ToString("0.0"));
                config.InfoLine3 = String.Format("Field Center: RA={0} DE={1}", AstroConvert.ToStringValue(m_RA, "HHh MMm SSs"), AstroConvert.ToStringValue(m_DE, "+DDo MM' SS\""));
                config.InfoLine4 = "";

                ThreadPool.QueueUserWorkItem(new WaitCallback(GenerateSimulatedVideo), config);
            }
        }
コード例 #34
0
        /// <summary>
        /// Reconstructs graph from config object.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        static (Tensors, Tensors, Dictionary <string, ILayer>) reconstruct_from_config(ModelConfig config)
        {
            // Layer instances created during the graph reconstruction process.
            var created_layers      = new Dictionary <string, ILayer>();
            var node_index_map      = new Dictionary <(string, int), int>();
            var node_count_by_layer = new Dictionary <ILayer, int>();
            var unprocessed_nodes   = new Dictionary <ILayer, NodeConfig>();

            // First, we create all layers and enqueue nodes to be processed
            foreach (var layer_data in config.Layers)
            {
                process_layer(created_layers, layer_data, unprocessed_nodes, node_count_by_layer);
            }

            // Then we process nodes in order of layer depth.
            // Nodes that cannot yet be processed (if the inbound node
            // does not yet exist) are re-enqueued, and the process
            // is repeated until all nodes are processed.
            while (unprocessed_nodes.Count > 0)
            {
                foreach (var layer_data in config.Layers)
                {
                    var layer = created_layers[layer_data.Name];
                    if (unprocessed_nodes.ContainsKey(layer))
                    {
                        var node_data = unprocessed_nodes[layer];
                        // foreach (var node_data in unprocessed_nodes[layer])
                        {
                            process_node(layer, node_data, created_layers, node_count_by_layer, node_index_map);
                            unprocessed_nodes.Remove(layer);
                        }
                    }
                }
            }

            var input_tensors = new List <Tensor>();

            foreach (var layer_data in config.InputLayers)
            {
                var(layer_name, node_index, tensor_index) = (layer_data.Name, layer_data.NodeIndex, layer_data.TensorIndex);
                var layer = created_layers[layer_name];
                var layer_output_tensors = layer.InboundNodes[node_index].Outputs;
                input_tensors.append(layer_output_tensors[tensor_index]);
            }

            var output_tensors = new List <Tensor>();

            foreach (var layer_data in config.OutputLayers)
            {
                var(layer_name, node_index, tensor_index) = (layer_data.Name, layer_data.NodeIndex, layer_data.TensorIndex);
                var layer = created_layers[layer_name];
                var layer_output_tensors = layer.InboundNodes[node_index].Outputs;
                output_tensors.append(layer_output_tensors[tensor_index]);
            }

            return(input_tensors, output_tensors, created_layers);
        }