Example #1
0
    def __init__(self, game):
        self.game = game  # allows access to the whole game object
        self.sleep_time = 0.05

        self.backpos = (0.03 * self.game.sx, 0.93 * self.game.sy)
        self.hback = 0.08 * self.game.sx
        self.vback = 0.05 * self.game.sy

        # The specifications of the grid
        self.reference = 0.9 * min([self.game.sx, self.game.sy])
        self.game_unit = self.reference / 100  # the in-game units, instead of pixels
        self.xcoord = 0.5 * (max([self.game.sx, self.game.sy]) -
                             self.reference)
        self.ycoord = 0.05 * self.reference

        # -----------------------------------------------------------------------------------------
        # THE MAIN GRAPHICS OBJECTS WILL BE STORED

        self.laser = Laser(self)
        self.materials = Materials(self, self.laser)

        # -----------------------------------------------------------------------------------------
        # Auxillary utilities
        # -----------------------------------------------------------------------------------------
        self.score_displayed = False
        self.score_window = (0.31 * self.game.sx, 0.30 * self.game.sy)
        self.score_size = (0.56 * self.reference, 0.45 * self.reference)
        self.score = 0
Example #2
0
    def __init__(self, input):

        # Store input parameters and check them
        self.input = input
        self.input.checkInputs()

        # Define geometry based on geometry input type
        if input.geometry == 'slab':
            self.geo = SlabGeometry(self)
        elif input.geometry == 'cylindrical':
            self.geo = CylindricalGeometry(self)
        else:
            self.geo = SphericalGeometry(self)

        # Initialize material handler now that geometry is initialized
        self.mat = Materials(self)

        # Initialize field variables
        self.fields = Fields(self)

        # Time step
        self.timeSteps = []

        # Initialize the radiation and hydro problems
        self.hydro = LagrangianHydro(self)
        self.radPredictor = LagrangianRadiationPredictor(self)
        self.radCorrector = LagrangianRadiationCorrector(self)
Example #3
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.setWindowTitle("NeutronPy")

        #We'll be using GridLayout so each pyqt instances such as Beamline, Materials, ImageViewer, Spectrum
        #can be displayed in their corresponding position as we desire
        layout = QGridLayout()

        #Creating an instance of these classes for our window
        #Robust so we can create multiply main.py windows for different operations in the future
        #TODO: Robustness to create new separate main windows for other imaging experiments
        beamline = Beamline()
        materials = Materials()
        imageviewer = ImageViewerWindow()
        spectrum = Spectrum(beamline, materials, imageviewer)

        #Defining where these instances go on the grid
        layout.addWidget(beamline, 0, 4, 1, 1)
        layout.addWidget(materials, 2, 2, 1, 3)
        layout.addWidget(spectrum, 0, 2, 2, 2)
        layout.addWidget(imageviewer, 0, 0, 3, 2)

        #Preset height and width
        height = 800
        width = 1550
        self.setMinimumSize(width, height)

        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)
Example #4
0
    def __init__(self):
        """Initialize the game, and create game resources"""
        pygame.init()
        self.music = Music()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Save the City")
        self.statistics_image = pygame.image.load('resources/stats.png')

        # Reading the score from disk
        # d = shelve.open('resources/high_score')
        # score = d['saved_score']
        # Create an instance to store game statistics-
        # -and create a scoreboard.
        self.stats = GameStats(self, 0)
        self.sb = Scoreboard(self)

        self.materials = Materials(self, self.settings.difficulty_level)
        self.worker = Worker(self)

        # Cooldown for collecting resources
        self.last = pygame.time.get_ticks()
        self.cooldown = 0
        # List for obtained values
        self.obtained_list = [False, False, False, False, False]

        # Make the play button
        self.play_button = Button(self, "Play")

        self.show = None
Example #5
0
    def __init__(self):
        self.wline = None
        self.wrect = None
        self.wcirc = None
        self.warc = None
        self.wpolygon = None
        self.wpolyline = None
        self.wrslot = None
        self.wdrillrect = None
        self.wdrillcirc = None
        self.wdrillline = None
        self.wgrid = None
        self.wdiamonds = None
        self.whatch = None

        self.modified = False

        wx.Frame.__init__(self,
                          None,
                          size=(480, 800),
                          title="G Code Generators - Main Menu")
        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.SetBackgroundColour("white")

        self.settings = Settings(self, cmdFolder)
        self.tools = Tools("tools.json")
        self.toolList = self.tools.getTools()
        if self.settings.tool not in self.toolList:
            self.settings.tool = self.toolList[0]
            self.settings.setModified()
        self.toolInfo = self.tools.getTool(self.settings.tool)

        self.images = Images(os.path.join(cmdFolder, "images"))

        self.materials = Materials()
        self.materialList = self.materials.getMaterials()
        if self.settings.material not in self.materialList:
            self.settings.material = self.materialList[0]
            self.settings.setModified()
        self.speedInfo = self.tools.getToolSpeeds(self.settings.tool,
                                                  self.settings.material)

        self.CreateStatusBar()

        menuBar = wx.MenuBar()

        self.menuFile = wx.Menu()
        self.menuFile.Append(MENU_FILE_VIEW, "&View", "View a G Code File")
        self.menuFile.Append(MENU_FILE_MERGE, "&Merge", "Merge G Code Files")
        menuBar.Append(self.menuFile, "&File")

        self.menuOpts = wx.Menu()
        self.menuOpts.Append(MENU_OPTS_ANNOTATE, "&Annotate",
                             "Annotate G Code", wx.ITEM_CHECK)
        self.menuOpts.Append(MENU_OPTS_ADD_SPEED, "A&dd Speed Term",
                             "Default setting for add speed term",
                             wx.ITEM_CHECK)
        self.menuOpts.Append(MENU_OPTS_METRIC, "&Metric",
                             "Use Metric Measurement System", wx.ITEM_CHECK)
        menuBar.Append(self.menuOpts, "&Options")

        self.menuMaterials = wx.Menu()
        mx = 0
        for m in self.materialList:
            mid = MENU_MATERIALS_BASE + mx
            self.menuMaterials.Append(mid, m, "Material: {}".format(m),
                                      wx.ITEM_RADIO)
            if m == self.settings.material:
                self.menuMaterials.Check(mid, True)
            self.Bind(wx.EVT_MENU, self.onMenuMaterials, id=mid)
            mx += 1

        menuBar.Append(self.menuMaterials, "&Material")

        self.menuTools = wx.Menu()
        tx = 0
        for t in self.toolList:
            tinfo = self.tools.getTool(t)
            tid = MENU_TOOLS_BASE + tx
            self.menuTools.Append(tid, t, "{}".format(tinfo["name"]),
                                  wx.ITEM_RADIO)
            if t == self.settings.tool:
                self.menuTools.Check(tid, True)
            self.Bind(wx.EVT_MENU, self.onMenuTools, id=tid)
            tx += 1

        menuBar.Append(self.menuTools, "&Tool")

        self.SetMenuBar(menuBar)
        self.Bind(wx.EVT_MENU, self.onMenuFileView, id=MENU_FILE_VIEW)
        self.Bind(wx.EVT_MENU, self.onMenuFileMerge, id=MENU_FILE_MERGE)
        self.Bind(wx.EVT_MENU, self.onMenuOptsAnnotate, id=MENU_OPTS_ANNOTATE)
        self.Bind(wx.EVT_MENU, self.onMenuOptsAddSpeed, id=MENU_OPTS_ADD_SPEED)
        self.Bind(wx.EVT_MENU, self.onMenuOptsMetric, id=MENU_OPTS_METRIC)

        self.menuOpts.Check(MENU_OPTS_ANNOTATE, self.settings.annotate)
        self.menuOpts.Check(MENU_OPTS_ADD_SPEED, self.settings.addspeed)
        self.menuOpts.Check(MENU_OPTS_METRIC, self.settings.metric)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        msizer = wx.BoxSizer(wx.VERTICAL)

        boxCont = wx.StaticBox(self, wx.ID_ANY, " Contours ")
        topBorder = boxCont.GetBordersForSizer()[0]
        bsizer = wx.BoxSizer(wx.VERTICAL)
        bsizer.AddSpacer(topBorder)

        szContours = wx.BoxSizer(wx.HORIZONTAL)
        szContours.AddSpacer(10)

        self.bLine = wx.BitmapButton(boxCont,
                                     wx.ID_ANY,
                                     self.images.pngContourline,
                                     size=BTNDIM)
        self.bLine.SetToolTip("Generate G Code for a straight line")
        szContours.Add(self.bLine)
        self.Bind(wx.EVT_BUTTON, self.bLinePressed, self.bLine)

        self.bRect = wx.BitmapButton(boxCont,
                                     wx.ID_ANY,
                                     self.images.pngContourrectangle,
                                     size=BTNDIM)
        self.bRect.SetToolTip("Generate G Code for a rectangle")
        szContours.Add(self.bRect)
        self.Bind(wx.EVT_BUTTON, self.bRectPressed, self.bRect)

        self.bCirc = wx.BitmapButton(boxCont,
                                     wx.ID_ANY,
                                     self.images.pngContourcircle,
                                     size=BTNDIM)
        self.bCirc.SetToolTip("Generate G Code for a circle")
        szContours.Add(self.bCirc)
        self.Bind(wx.EVT_BUTTON, self.bCircPressed, self.bCirc)

        self.bArc = wx.BitmapButton(boxCont,
                                    wx.ID_ANY,
                                    self.images.pngContourarc,
                                    size=BTNDIM)
        self.bArc.SetToolTip("Generate G Code for an arc")
        szContours.Add(self.bArc)
        self.Bind(wx.EVT_BUTTON, self.bArcPressed, self.bArc)

        self.bPolygon = wx.BitmapButton(boxCont,
                                        wx.ID_ANY,
                                        self.images.pngContourpolygon,
                                        size=BTNDIM)
        self.bPolygon.SetToolTip("Generate G Code for a regular polygon")
        szContours.Add(self.bPolygon)
        self.Bind(wx.EVT_BUTTON, self.bPolygonPressed, self.bPolygon)

        self.bPolyline = wx.BitmapButton(boxCont,
                                         wx.ID_ANY,
                                         self.images.pngContourpolyline,
                                         size=BTNDIM)
        self.bPolyline.SetToolTip("Generate G Code for an open or close path")
        szContours.Add(self.bPolyline)
        self.Bind(wx.EVT_BUTTON, self.bPolylinePressed, self.bPolyline)

        self.bRSlot = wx.BitmapButton(boxCont,
                                      wx.ID_ANY,
                                      self.images.pngContourroundedslot,
                                      size=BTNDIM)
        self.bRSlot.SetToolTip("Generate G Code for a rounded slot")
        szContours.Add(self.bRSlot)
        self.Bind(wx.EVT_BUTTON, self.bRSlotPressed, self.bRSlot)

        szContours.AddSpacer(10)

        bsizer.Add(szContours)
        bsizer.AddSpacer(10)
        boxCont.SetSizer(bsizer)
        msizer.Add(boxCont, weightSingle, wx.EXPAND | wx.ALL, 10)

        boxDrills = wx.StaticBox(self, wx.ID_ANY, " Drills ")
        topBorder = boxDrills.GetBordersForSizer()[0]
        bsizer = wx.BoxSizer(wx.VERTICAL)
        bsizer.AddSpacer(topBorder)

        szDrills = wx.BoxSizer(wx.HORIZONTAL)

        szDrills.AddSpacer(10)

        self.bDrillRect = wx.BitmapButton(boxDrills,
                                          wx.ID_ANY,
                                          self.images.pngDrillrectangle,
                                          size=BTNDIM)
        self.bDrillRect.SetToolTip(
            "Generate G Code for a rectangular drill pattern")
        szDrills.Add(self.bDrillRect)
        self.Bind(wx.EVT_BUTTON, self.bDrillRectPressed, self.bDrillRect)

        self.bDrillCirc = wx.BitmapButton(boxDrills,
                                          wx.ID_ANY,
                                          self.images.pngDrillcircle,
                                          size=BTNDIM)
        self.bDrillCirc.SetToolTip(
            "Generate G Code for a circular drill pattern")
        szDrills.Add(self.bDrillCirc)
        self.Bind(wx.EVT_BUTTON, self.bDrillCircPressed, self.bDrillCirc)

        self.bDrillLine = wx.BitmapButton(boxDrills,
                                          wx.ID_ANY,
                                          self.images.pngDrilllinear,
                                          size=BTNDIM)
        self.bDrillLine.SetToolTip(
            "Generate G Code for a linear drill pattern")
        szDrills.Add(self.bDrillLine)
        self.Bind(wx.EVT_BUTTON, self.bDrillLinePressed, self.bDrillLine)

        bsizer.Add(szDrills)
        bsizer.AddSpacer(10)
        boxDrills.SetSizer(bsizer)
        msizer.Add(boxDrills, weightSingle, wx.EXPAND | wx.ALL, 10)

        boxCarve = wx.StaticBox(self, wx.ID_ANY, " Carvings ")
        topBorder = boxCarve.GetBordersForSizer()[0]
        bsizer = wx.BoxSizer(wx.VERTICAL)
        bsizer.AddSpacer(topBorder)

        szCarving = wx.BoxSizer(wx.HORIZONTAL)

        szCarving.AddSpacer(10)

        self.bGrid = wx.BitmapButton(boxCarve,
                                     wx.ID_ANY,
                                     self.images.pngCarvegrid,
                                     size=BTNDIM)
        self.bGrid.SetToolTip("Generate G Code for a grid pattern")
        szCarving.Add(self.bGrid)
        self.Bind(wx.EVT_BUTTON, self.bGridPressed, self.bGrid)

        self.bDiamonds = wx.BitmapButton(boxCarve,
                                         wx.ID_ANY,
                                         self.images.pngCarvediamond,
                                         size=BTNDIM)
        self.bDiamonds.SetToolTip("Generate G Code for a diamond pattern")
        szCarving.Add(self.bDiamonds)
        self.Bind(wx.EVT_BUTTON, self.bDiamondPressed, self.bDiamonds)

        self.bHatch = wx.BitmapButton(boxCarve,
                                      wx.ID_ANY,
                                      self.images.pngCarvehatch,
                                      size=BTNDIM)
        self.bHatch.SetToolTip("Generate G Code for a cross-hatch pattern")
        szCarving.Add(self.bHatch)
        self.Bind(wx.EVT_BUTTON, self.bHatchPressed, self.bHatch)

        bsizer.Add(szCarving)
        bsizer.AddSpacer(10)
        boxCarve.SetSizer(bsizer)
        msizer.Add(boxCarve, weightSingle, wx.EXPAND | wx.ALL, 10)

        sizer.Add(msizer)

        sizer.AddSpacer(10)

        self.SetSizer(sizer)
        self.Layout()
        self.Fit()
Example #6
0
        size=(53.3, 38.7)
        )
    space.add_subject(detector)

    collimator = SiemensSymbiaTSeriesLEHR(
        coordinates=(detector.coordinates[0], detector.coordinates[1], detector.size[2] + 0.5),
        size=detector.size[:2]
        )
    space.add_subject(collimator)

    source = efg3(
        coordinates=phantom.coordinates,
        activity=300*10**6,
        )

    materials = Materials(materials, max_energy=source.energy)

    materials.table = np.array([7, 7, 7, 10, 32, 82])

    for angle in angles:
        phantom.rotate((0., angle, 0.))
        source.rotate((0., angle, 0.))
        
        modeling = Modeling(
            space,
            source,
            materials,
            stop_time=0.1,
            particles_number=10**6,
            flow_number=2,
            file_name=f'efg3_full_angle {round(angle*180/np.pi, 1)} deg.hdf',
Example #7
0
def main():
    angles = np.linspace(-np.pi/4, 3*np.pi/4, 32)
    projection_time = 15
    pause_time = 1.

    materials = {
        'Compounds and mixtures/Air, Dry (near sea level)':         0,
        'Compounds and mixtures/Lung':                              1,
        'Compounds and mixtures/Tissue, Soft (ICRU-44)':            2,
        'Compounds and mixtures/B-100 Bone-Equivalent Plastic':     3,
        'Compounds and mixtures/Sodium Iodide':                     4,
        'Elemental media/Pb':                                       5,
    }

    space = Space(
        size=(51.2, 40., 60.),
        material=0
        )

    detector = SiemensSymbiaTSeries3_8(
        coordinates=(0., 0., 0),
        size=space.size[:2]
        )

    collimator = SiemensSymbiaTSeriesLEHR(
        coordinates=(detector.coordinates[0], detector.coordinates[1], detector.size[2] + 0.5),
        size=detector.size[:2]
        )

    phantom = ae3cut(
        coordinates=(collimator.coordinates[0], collimator.coordinates[1], collimator.size[2]),
        )

    source = SourceManager().efg3cut(
        coordinates=phantom.coordinates,
        activity=300*10**6,
        )

    space.add_subject(phantom)    
    space.add_subject(detector)
    space.add_subject(collimator)

    materials = Materials(materials, max_energy=source.energy)

    materials.table = np.array([7, 7, 7, 10, 32, 82])

    for angle in angles:
        phantom.rotate((0., angle, 0.))
        source.rotate((0., angle, 0.))
        
        modeling = Modeling(
            space,
            source,
            materials,
            stop_time=source.timer + projection_time,
            particles_number=10**8,
            flow_number=8,
            file_name=f'efg3cut/{round(np.rad2deg(angle), 1)} deg.hdf',
            iteraction_buffer=10**4,
            subject=detector
            )
        
        modeling.start()
        modeling.join()
        source.set_state(source.timer + pause_time)
Example #8
0
    def create_evaluable(self, expression, try_equations=True, auto_init=False,
                         preserve_caches=False, copy_materials=True,
                         integrals=None,
                         ebcs=None, epbcs=None, lcbcs=None,
                         ts=None, functions=None,
                         mode='eval', var_dict=None, strip_variables=True,
                         extra_args=None, verbose=True, **kwargs):
        """
        Create evaluable object (equations and corresponding variables)
        from the `expression` string. Convenience function calling
        :func:`create_evaluable()
        <sfepy.discrete.evaluate.create_evaluable()>` with defaults provided
        by the Problem instance `self`.

        The evaluable can be repeatedly evaluated by calling
        :func:`eval_equations() <sfepy.discrete.evaluate.eval_equations()>`,
        e.g. for different values of variables.

        Parameters
        ----------
        expression : str
            The expression to evaluate.
        try_equations : bool
            Try to get variables from `self.equations`. If this fails,
            variables can either be provided in `var_dict`, as keyword
            arguments, or are created automatically according to the
            expression.
        auto_init : bool
            Set values of all variables to all zeros.
        preserve_caches : bool
            If True, do not invalidate evaluate caches of variables.
        copy_materials : bool
            Work with a copy of `self.equations.materials` instead of
            reusing them. Safe but can be slow.
        integrals : Integrals instance, optional
            The integrals to be used. Automatically created as needed if
            not given.
        ebcs : Conditions instance, optional
            The essential (Dirichlet) boundary conditions for 'weak'
            mode. If not given, `self.ebcs` are used.
        epbcs : Conditions instance, optional
            The periodic boundary conditions for 'weak'
            mode. If not given, `self.epbcs` are used.
        lcbcs : Conditions instance, optional
            The linear combination boundary conditions for 'weak'
            mode. If not given, `self.lcbcs` are used.
        ts : TimeStepper instance, optional
            The time stepper. If not given, `self.ts` is used.
        functions : Functions instance, optional
            The user functions for boundary conditions, materials
            etc. If not given, `self.functions` are used.
        mode : one of 'eval', 'el_avg', 'qp', 'weak'
            The evaluation mode - 'weak' means the finite element
            assembling, 'qp' requests the values in quadrature points,
            'el_avg' element averages and 'eval' means integration over
            each term region.
        var_dict : dict, optional
            The variables (dictionary of (variable name) : (Variable instance))
            to be used in the expression. Use this if the name of a variable
            conflicts with one of the parameters of this method.
        strip_variables : bool
            If False, the variables in `var_dict` or `kwargs` not present in
            the expression are added to the actual variables as a context.
        extra_args : dict, optional
            Extra arguments to be passed to terms in the expression.
        verbose : bool
            If False, reduce verbosity.
        **kwargs : keyword arguments
            Additional variables can be passed as keyword arguments, see
            `var_dict`.

        Returns
        -------
        equations : Equations instance
            The equations that can be evaluated.
        variables : Variables instance
            The corresponding variables. Set their values and use
            :func:`eval_equations() <sfepy.discrete.evaluate.eval_equations()>`.

        Examples
        --------
        `problem` is Problem instance.

        >>> out = problem.create_evaluable('dq_state_in_volume_qp.i1.Omega(u)')
        >>> equations, variables = out

        `vec` is a vector of coefficients compatible with the field
        of 'u' - let's use all ones.

        >>> vec = nm.ones((variables['u'].n_dof,), dtype=nm.float64)
        >>> variables['u'].set_data(vec)
        >>> vec_qp = eval_equations(equations, variables, mode='qp')

        Try another vector:

        >>> vec = 3 * nm.ones((variables['u'].n_dof,), dtype=nm.float64)
        >>> variables['u'].set_data(vec)
        >>> vec_qp = eval_equations(equations, variables, mode='qp')
        """
        from sfepy.discrete.equations import get_expression_arg_names

        variables = get_default(var_dict, {})
        var_context = get_default(var_dict, {})

        if try_equations and self.equations is not None:
            # Make a copy, so that possible variable caches are preserved.
            for key, var in self.equations.variables.as_dict().iteritems():
                if key in variables:
                    continue
                var = var.copy(name=key)
                if not preserve_caches:
                    var.clear_evaluate_cache()
                variables[key] = var

        elif var_dict is None:
            possible_var_names = get_expression_arg_names(expression)
            variables = self.create_variables(possible_var_names)

        materials = self.get_materials()
        if materials is not None:
            if copy_materials:
                materials = materials.semideep_copy()

            else:
                materials = Materials(objs=materials._objs)

        else:
            possible_mat_names = get_expression_arg_names(expression)
            materials = self.create_materials(possible_mat_names)

        _kwargs = copy(kwargs)
        for key, val in kwargs.iteritems():
            if isinstance(val, Variable):
                if val.name != key:
                    msg = 'inconsistent variable name! (%s == %s)' \
                          % (val.name, key)
                    raise ValueError(msg)
                var_context[key] = variables[key] = val.copy(name=key)
                _kwargs.pop(key)

            elif isinstance(val, Material):
                if val.name != key:
                    msg = 'inconsistent material name! (%s == %s)' \
                          % (val.name, key)
                    raise ValueError(msg)
                materials[val.name] = val
                _kwargs.pop(key)

        kwargs = _kwargs

        ebcs = get_default(ebcs, self.ebcs)
        epbcs = get_default(epbcs, self.epbcs)
        lcbcs = get_default(lcbcs, self.lcbcs)
        ts = get_default(ts, self.get_timestepper())
        functions = get_default(functions, self.functions)
        integrals = get_default(integrals, self.get_integrals())

        out = create_evaluable(expression, self.fields, materials,
                               variables.itervalues(), integrals,
                               ebcs=ebcs, epbcs=epbcs, lcbcs=lcbcs,
                               ts=ts, functions=functions,
                               auto_init=auto_init,
                               mode=mode, extra_args=extra_args, verbose=verbose,
                               kwargs=kwargs)

        if not strip_variables:
            variables = out[1]
            variables.extend([var for var in var_context.itervalues()
                              if var not in variables])

        equations = out[0]
        mode = 'update' if not copy_materials else 'normal'
        equations.time_update_materials(self.ts, mode=mode, problem=self,
                                        verbose=verbose)

        return out
Example #9
0
    def __init__(self, input):

        # Store input parameters and check them
        self.input = input
        self.input.checkInputs()

        # Define geometry based on geometry input type
        if input.geometry == 'slab':
            self.geo = SlabGeometry(self)
        elif input.geometry == 'cylindrical':
            self.geo = CylindricalGeometry(self)
        else:
            self.geo = SphericalGeometry(self)

        # Initialize material handler now that geometry is initialized
        self.mat = Materials(self)

        # Initialize field variables
        self.fields = Fields(self)

        # Time parameters
        self.timeSteps = []
        self.time = 0.
        self.timeStep_num = 0
        self.Tf = input.Tf

        # Initialize hydro problem
        self.hydro = LagrangianHydro(self)

        # Initialize radiation problem (if used)
        self.radPredictor = LagrangianRadiationPredictor(self)
        self.radCorrector = LagrangianRadiationCorrector(self)

        # Init storage for energies in conservation check
        self.kinetic_energy = []
        self.internal_energy = []
        self.radiation_energy = []
        self.radiation_leakage = []
        self.work_energy = []
        self.total_energy = []

        # Compute initial energies for each
        kinetic = 0
        internal = 0
        radiation = 0
        for i in range(self.geo.N + 1):
            kinetic += 1 / 2 * self.mat.m_half[i] * self.fields.u_IC[i]**2

            if i < self.geo.N:
                internal += self.mat.m[i] * self.fields.e_IC[i]
                radiation += self.mat.m[i] * self.fields.E_IC[
                    i] / self.fields.rho_IC[i]
        total = kinetic + internal + radiation

        self.kinetic_energy.append(kinetic)
        self.internal_energy.append(internal)
        self.radiation_energy.append(radiation)
        self.radiation_leakage.append(0)
        self.work_energy.append(0)
        self.total_energy.append(total)

        self.total_radiation_leakage = 0
        self.total_work_energy = 0
Example #10
0
def save():
    filename = 'office_' + time.strftime('%Y-%m-%d_%H-%M-%S') + '.blend'
    bpy.ops.wm.save_as_mainfile(filepath=filename,
                                check_existing=False,
                                copy=True)
    print("Office saved as %s", filename)
    print("Now you can generate another environment again!\n")


class Office:
    def __init__(self, ogF):
        self.officeGrammarFile = ogF
        self.officeGrammar = Grammar(self.officeGrammarFile)
        self.proceduralMachine = ProceduralGeometry(
            self.officeGrammar.roomsL, self.officeGrammar.roomsR,
            self.officeGrammar.noise, self.officeGrammar.meeting,
            self.officeGrammar.bathroom)

    def makeOffice(self, sub):
        officeGrammarStr = self.officeGrammar.deriveString(sub)
        self.proceduralMachine.generateGeometry(officeGrammarStr)


#Procedurally generate office environment
clearScene()  #Remove everything
Materials().generateNewMaterials()  #Generate materials
office = Office("grammar.grammar")  #Set grammars
office.makeOffice(
    4)  #Start generating office with n (from 1 to 4) levels of detail
save()  #saves result in a new blend file
Example #11
0
    def lose_materials(self, material):
        losed = {}
        m = material.materials_list()
        k = random.randint(1, 3)
        names = random.choices(m, k=k)
        for i in names:
            amount = random.randrange(-50, -1)
            losed[i] = amount
        # zmienic morale
        return losed

    def injure_person(self, person, injure_kind):
        # zmienic morale
        pass


if __name__ == '__main__':
    from materials import Materials
    m = Materials()
    e = Event()

    znaleziono = e.found_materials(m)
    print(znaleziono)
    m.materials_change(znaleziono)
    print(m.materials_status())

    stracono = e.lose_materials(m)
    print(stracono)
    m.materials_change(stracono)
    print(m.materials_status())