Ejemplo n.º 1
0
    def step(self, mcs):
        for cell in self.cell_list:
            if cell.type == 3:
                pt = CompuCell.Point3D()
                for x in range(9, 17):
                    for y in range(9, 17):
                        pt.x = x
                        pt.y = y
                        if int(self.boundary_array.get(pt)):
                            print('pt=', pt, ' boundary=',
                                  int(self.boundary_array.get(pt)))
            if not self.pixel_assigned:
                pt = CompuCell.Point3D(12, 12, 0)
                self.cell_field.set(pt, self.medium_cell)
                self.pixel_assigned = True
            if mcs == 3:
                self.cell_field[12, 12, 0] = cell
                print('REASSIGNMNET COMPLETED')

            if mcs == 4:
                self.cell_field[12, 10, 0] = self.medium_cell

            if mcs == 5:
                self.cell_field[12, 11, 0] = self.medium_cell

            break
Ejemplo n.º 2
0
    def __init__(self, inventory, *args):
        self.inventory = inventory

        self.types = CompuCell.vectorint()

        self.inventoryByType = CompuCell.mapLongCellGPtr()

        self.initTypeVec(args)
        self.inventory.initCellInventoryByMultiType(self.inventoryByType,
                                                    self.types)
    def copy_sbml_simulators(self, from_cell: object, to_cell: object, sbml_names: Union[list, None] = None,
                             options: Union[dict, None] = None):
        """
        Copies SBML solvers (with their states - effectively clones the solver) from one cell to another
        :param from_cell: source CellG cell
        :param to_cell: target CellG cell
        :param sbml_names: list of SBML model name whose solver are to be copied
        :param options: - deprecated - list of SBML solver options
        :return: None
        """
        sbml_names = self.__default_mutable_type(sbml_names, [])
        options = self.__default_mutable_type(options, {})

        sbml_names_to_copy = []
        if not (len(sbml_names)):
            # if user does not specify _sbmlNames we copy all SBML networks
            try:
                dict_attrib = CompuCell.getPyAttrib(from_cell)
                sbml_dict = dict_attrib['SBMLSolver']
                sbml_names_to_copy = list(sbml_dict.keys())
            except LookupError as e:
                pass
        else:
            sbml_names_to_copy = sbml_names

        try:
            dict_attrib_from = CompuCell.getPyAttrib(from_cell)
            sbml_dict_from = dict_attrib_from['SBMLSolver']
        except LookupError:
            return

        try:
            dict_attrib_to = CompuCell.getPyAttrib(to_cell)
            # sbml_dict_to = dict_attrib_to['SBMLSolver']
        except LookupError:
            pass
            # if _toCell does not have SBMLSolver dictionary entry we simply add it
            # dict_attrib_to['SBMLSolver'] = {}
            # sbml_dict_to = dict_attrib_to['SBMLSolver']

        for sbml_name in sbml_names_to_copy:
            rr_from = sbml_dict_from[sbml_name]
            current_state_sbml = sbml_dict_from[sbml_name].getCurrentSBML()
            self.add_sbml_to_cell(
                model_file=rr_from.path,  # necessary to get deserialization working properly
                model_name=sbml_name,
                cell=to_cell,
                step_size=rr_from.stepSize,
                options=options,
                current_state_sbml=current_state_sbml
            )
Ejemplo n.º 4
0
def extra_init_simulation_objects(sim,
                                  simthread,
                                  init_using_restart_snapshot_enabled=False):
    """
    Performs extra initializations. Also checks for validity of concentration field names (those defined in C++)
    :param sim:
    :param simthread:
    :param init_using_restart_snapshot_enabled:
    :return:
    """

    # after all xml steppables and plugins have been loaded we call extraInit to complete initialization
    sim.extraInit()
    concentration_field_names = CompuCell.getConcentrationFieldNames(sim)
    for conc_field_name in concentration_field_names:
        validate_cc3d_entity_identifier(
            entity_identifier=conc_field_name,
            entity_type_label='Concentration Field Label')

    # passing output directory to simulator object
    sim.setOutputDirectory(CompuCellSetup.persistent_globals.output_directory)
    # simthread.preStartInit()
    # we skip calling start functions of steppables if restart is enabled and we are using restart
    # directory to restart simulation from a given MCS
    if not init_using_restart_snapshot_enabled:
        sim.start()

    if simthread is not None:
        # sends signal to player  to prepare for the upcoming simulation
        simthread.postStartInit()

        # waits for player  to complete initialization
        simthread.waitForPlayerTaskToFinish()
Ejemplo n.º 5
0
    def step(self, mcs):
        if self.pixel_tracker_plugin is None:
            return

        # Test modification of field values outside of core routines
        mcs_change_rate = 10e3
        if mcs % mcs_change_rate == 0:
            for cell in self.cell_list:
                new_val = random.random()
                for ptd in self.get_cell_pixel_list(cell):
                    self.yes_fluc_comp[ptd.pixel.x, ptd.pixel.y, 0] = new_val
                    self.no_fluc_comp[ptd.pixel.x, ptd.pixel.y, 0] = new_val

            # Without this call, modifications (other than by core routines) to a field with a solver using
            # FluctuationCompensator will likely cause numerical errors
            CompuCell.updateFluctuationCompensators()
Ejemplo n.º 6
0
 def __init__(self, _cellList):
     self.inventory = _cellList.inventory
     self.invItr = CompuCell.compartmentinventoryPtrPyItr()
     self.invItr.initialize(self.inventory)
     self.invItr.setToBegin()
     self.compartmentList = None
     self.next = self.__next__
    def delete_sbml_from_cell_ids(self, model_name: str, cell_ids: Union[None, list] = None) -> None:
        """
        Deletes  SBML model from cells whose ids match those stered int he _ids list
        :param model_name: model name
        :param cell_ids: list of cell ids
        :return:
        """
        """

        :param _modelName {str}: 
        :param _ids {list}: 
        :return: None
        """
        cell_ids = self.__default_mutable_type(cell_ids, [])

        for cell_id in cell_ids:
            cell = self.inventory.attemptFetchingCellById(cell_id)
            if not cell:
                continue

            dict_attrib = CompuCell.getPyAttrib(cell)
            try:
                sbml_dict = dict_attrib['SBMLSolver']
                del sbml_dict[model_name]
            except LookupError as e:
                pass
Ejemplo n.º 8
0
 def __init__(self, _cellNeighborList):
     self.neighborTrackerAccessor = _cellNeighborList.neighborTrackerAccessor
     self.cell = _cellNeighborList.cell
     self.nsdItr = CompuCell.nsdSetPyItr()
     self.nTracker = self.neighborTrackerAccessor.get(
         self.cell.extraAttribPtr)
     self.nsdItr.initialize(self.nTracker.cellNeighbors)
     self.nsdItr.setToBegin()
Ejemplo n.º 9
0
    def read_simulation_data_non_blocking(self, file_number: int) -> bool:
        """
        reads content of the serialized file
        :param file_number: {int}
        :return: {bool} flag whether read was successful or not
        """

        # this flag is used to prevent calling  draw function
        self.newFileBeingLoaded = True

        # when new data is read from hard drive
        if file_number >= len(self.ldsFileList):
            return False

        fileName = self.ldsFileList[file_number]

        self.simulationDataReader = vtk.vtkStructuredPointsReader()

        self.currentFileName = os.path.join(self.ldsDir, fileName)
        print('self.currentFileName=', self.currentFileName)

        extracted_mcs = self.extract_mcs_number_from_file_name(
            file_name=self.currentFileName)
        if extracted_mcs < 0:
            extracted_mcs = file_number

        self.simulationDataReader.SetFileName(self.currentFileName)
        # print "path= ", os.path.join(self.ldsDir,fileName)

        data_reader_int_addr = extract_address_int_from_vtk_object(
            vtkObj=self.simulationDataReader)

        # swig wrapper  on top of     vtkStructuredPointsReader.Update()  - releases GIL,
        # hence can be used in multithreaded program that does not block GUI
        self.__ui.fieldExtractor.readVtkStructuredPointsData(
            data_reader_int_addr)

        # # # self.simulationDataReader.Update() # does not erlease GIL - VTK ISSUE -
        # cannot be used in multithreaded program - blocks GUI
        self.simulationData = self.simulationDataReader.GetOutput()

        self.fieldDimPrevious = self.fieldDim
        # self.fieldDimPrevious=CompuCell.Dim3D()

        dim_from_vtk = self.simulationData.GetDimensions()

        self.fieldDim = CompuCell.Dim3D(dim_from_vtk[0], dim_from_vtk[1],
                                        dim_from_vtk[2])

        self.currentStep = extracted_mcs
        # # # self.currentStep = self.frequency * _i # this is how we set CMS for CML reading before
        self.setCurrentStep(self.currentStep)

        self.newFileBeingLoaded = False

        return True
Ejemplo n.º 10
0
    def __init__(self, _cellPixelList):

        self.pixelTrackerAccessor = _cellPixelList.pixelTrackerAccessor
        self.pixelTrackerPlugin = _cellPixelList.pixelTrackerPlugin
        self.cell = _cellPixelList.cell
        self.pixelItr = CompuCell.pixelSetPyItr()
        self.pixelTracker = self.pixelTrackerAccessor.get(
            self.cell.extraAttribPtr)
        self.pixelItr.initialize(self.pixelTracker.pixelSet)
        self.pixelItr.setToBegin()
Ejemplo n.º 11
0
 def __init__(self, elasticity_data_list):
     self.elasticity_tracker_accessor = elasticity_data_list.elasticity_tracker_accessor
     self.cell = elasticity_data_list.cell
     self.elasticity_tracker_plugin = elasticity_data_list.elasticity_tracker_plugin
     self.elasticity_tracker = self.elasticity_tracker_accessor.get(
         self.cell.extraAttribPtr)
     self.elasticity_data_set_itr = CompuCell.elasticitySetPyItr()
     self.elasticity_data_set_itr.initialize(
         self.elasticity_tracker.elasticityNeighbors)
     self.elasticity_data_set_itr.setToBegin()
def step_sbml_model_cell(cell, sbml_model_name=vr_model_name):
    """
    Steps SBML model for a cell
    :param cell: cell with a SBML model to step
    :param sbml_model_name: name of SBML model to step
    :return: None
    """
    dict_attrib = CompuCell.getPyAttrib(cell)
    assert 'SBMLSolver' in dict_attrib
    dict_attrib['SBMLSolver'][sbml_model_name].timestep()
Ejemplo n.º 13
0
 def __init__(self, plasticity_data_list):
     self.plasticityTrackerAccessor = plasticity_data_list.plasticityTrackerAccessor
     self.cell = plasticity_data_list.cell
     self.plasticity_tracker_plugin = plasticity_data_list.plasticity_tracker_plugin
     self.plasticityTracker = self.plasticityTrackerAccessor.get(
         self.cell.extraAttribPtr)
     self.plasticityDataSetItr = CompuCell.plasticitySetPyItr()
     self.plasticityDataSetItr.initialize(
         self.plasticityTracker.plasticityNeighbors)
     self.plasticityDataSetItr.setToBegin()
Ejemplo n.º 14
0
 def __init__(self, _focalPointPlasticityDataList):
     self.focalPointPlasticityTrackerAccessor = _focalPointPlasticityDataList.focalPointPlasticityTrackerAccessor
     self.cell = _focalPointPlasticityDataList.cell
     self.focalPointPlasticityPlugin = _focalPointPlasticityDataList.focalPointPlasticityPlugin
     self.focalPointPlasticityTracker = self.focalPointPlasticityTrackerAccessor.get(
         self.cell.extraAttribPtr)
     self.focalPointPlasticityDataSetItr = CompuCell.focalPointPlasticitySetPyItr(
     )
     self.focalPointPlasticityDataSetItr.initialize(
         self.focalPointPlasticityTracker.anchors)
     self.focalPointPlasticityDataSetItr.setToBegin()
Ejemplo n.º 15
0
def get_core_simulation_objects():
    persistent_globals = CompuCellSetup.persistent_globals

    simulator = CompuCell.Simulator()
    simthread = None
    # todo 5 - fix logic regarding simthread initialization
    if persistent_globals.simthread is not None:
        simthread = persistent_globals.simthread
        simulator.setNewPlayerFlag(True)

    simulator.setBasePath(
        join(dirname(persistent_globals.simulation_file_name)))

    xml_fname = CompuCellSetup.cc3dSimulationDataHandler.cc3dSimulationData.xmlScript

    if persistent_globals.cc3d_xml_2_obj_converter is None:
        # We only call parseXML if previous steps do not initialize XML tree
        # Such situation usually happen when we specify XML tree using Python API in configure_simulation function
        # that is typically called from the Python main script

        cc3d_xml2_obj_converter = parseXML(xml_fname=xml_fname)
        #  cc3d_xml2_obj_converter cannot be garbage colected hence goes to persisten storage
        #  declared at the global level in CompuCellSetup
        persistent_globals.cc3d_xml_2_obj_converter = cc3d_xml2_obj_converter

    # locating all XML elements with attribute id - presumably to be used for programmatic steering
    persistent_globals.xml_id_locator = XMLIdLocator(
        root_elem=persistent_globals.cc3d_xml_2_obj_converter.root)
    persistent_globals.xml_id_locator.locate_id_elements()

    init_modules(simulator, persistent_globals.cc3d_xml_2_obj_converter)

    # # this loads all plugins/steppables - need to recode it to make loading on-demand only
    CompuCell.initializePlugins()

    simulator.initializeCC3D()

    # sim.extraInit()

    return simulator, simthread
Ejemplo n.º 16
0
    def extract_lattice_dim_from_file_name(_lds_file) -> Dim3D:
        """
        Extract field dimensions from the xml that summarizes serialized simulation files
        :param _lds_file:{str} xml metadata file name
        :return: {Dim3D} field dimensions
        """
        lds_xml = _LatticeDataXMLReader(_lds_file)

        field_dim = CompuCell.Dim3D()
        field_dim.x = int(lds_xml.dim_element.getAttribute("x"))
        field_dim.y = int(lds_xml.dim_element.getAttribute("y"))
        field_dim.z = int(lds_xml.dim_element.getAttribute("z"))
        return field_dim
Ejemplo n.º 17
0
    def read_simulation_data(self, file_number: int) -> (bool, int):
        """
        reads content of the serialized file
        :param file_number: {int}
        :return: {(bool, int)} flag whether read was successful or not, extracted mcs
        """
        # By this point, either field extractor is set, or parent has cml field extractor
        if self.field_extractor is None:
            assert hasattr(self._parent, 'fieldExtractor') or hasattr(self._parent, 'field_extractor')
            if hasattr(self._parent, 'field_extractor'):
                _a = 'field_extractor'
            else:
                _a = 'fieldExtractor'
            self.field_extractor = getattr(self._parent, _a)
            assert isinstance(self.field_extractor, PlayerPython.FieldExtractorCML)

        # when new data is read from hard drive
        if file_number >= len(self.ldsFileList):
            return False, -1

        fileName = self.ldsFileList[file_number]

        self.simulationDataReader = vtk.vtkStructuredPointsReader()

        self.currentFileName = os.path.join(self.ldsDir, fileName)
        print('self.currentFileName=', self.currentFileName)

        extracted_mcs = self.extract_mcs_number_from_file_name(file_name=self.currentFileName)
        if extracted_mcs < 0:
            extracted_mcs = file_number

        self.simulationDataReader.SetFileName(self.currentFileName)

        data_reader_int_addr = extract_address_int_from_vtk_object(vtkObj=self.simulationDataReader)

        # swig wrapper  on top of     vtkStructuredPointsReader.Update()  - releases GIL,
        # hence can be used in multithreaded program that does not block GUI
        self.field_extractor.readVtkStructuredPointsData(data_reader_int_addr)

        # # # self.simulationDataReader.Update() # does not erlease GIL - VTK ISSUE -
        # limited use in multithreaded program - blocks GUI
        self.simulationData = self.simulationDataReader.GetOutput()

        self.fieldDimPrevious = self.fieldDim

        dim_from_vtk = self.simulationData.GetDimensions()

        self.fieldDim = CompuCell.Dim3D(dim_from_vtk[0], dim_from_vtk[1], dim_from_vtk[2])

        return True, extracted_mcs
    def delete_sbml_from_cell(self, model_name: str = '', cell: object = None) -> None:
        """
        Deletes SBML from a particular cell
        :param model_name: model name
        :param cell: CellG cell obj
        :return: None
        """

        dict_attrib = CompuCell.getPyAttrib(cell)
        try:
            sbml_dict = dict_attrib['SBMLSolver']
            del sbml_dict[model_name]
        except LookupError:
            pass
    def timestep_cell_sbml(self):
        """
        advances (integrats forward) models stored as attributes of cells
        :return: None
        """

        # time-stepping SBML attached to cells
        for cell in self.cellList:
            dict_attrib = CompuCell.getPyAttrib(cell)
            if 'SBMLSolver' in dict_attrib:
                sbml_dict = dict_attrib['SBMLSolver']

                for model_name, rrTmp in sbml_dict.items():
                    # integrating SBML
                    rrTmp.timestep()
Ejemplo n.º 20
0
    def start(self):
        """
        any code in the start function runs before MCS=0
        """

        # Generate plots for graphical reporting
        self.plot_win1 = self.add_new_plot_window(
            title='Total medium concentration',
            x_axis_title='Monte Carlo Step',
            y_axis_title='Total medium concentration',
            x_scale_type='linear',
            y_scale_type='linear',
            grid=True,
            config_options={'legend': True})
        self.plot_win1.add_plot("ConcPTPMed",
                                style='Dots',
                                color='red',
                                size=5)
        self.plot_win1.add_plot("ConcManMed",
                                style='Dots',
                                color='green',
                                size=5)
        self.plot_win1.add_plot("ConcMan", style='Dots', color='blue', size=5)

        # Create plot window for Cell 1 volume and surface
        self.plot_win2 = self.add_new_plot_window(
            title='Total medium concentration errors',
            x_axis_title='Monte Carlo Step',
            y_axis_title='Errors',
            x_scale_type='linear',
            y_scale_type='linear',
            grid=True,
            config_options={'legend': True})
        self.plot_win2.add_plot("ErrorConcPTPMed",
                                style='Dots',
                                color='red',
                                size=5)
        self.plot_win2.add_plot("ErrorConcManMod",
                                style='Dots',
                                color='green',
                                size=5)

        # Set all values to zero in cells
        f = CompuCell.getConcentrationField(self.simulator, "F1")
        for x, y, z in self.every_pixel():
            if self.cell_field[x, y, z]:
                f[x, y, z] = 0.0
    def set_step_size_for_cell(self, model_name: str = '', cell: object = None, step_size: float = 1.0):
        """
        Sets integration step size for SBML model attached to _cell

        :param model_name: model name
        :param cell: CellG cell object
        :param step_size: integration step size
        :return: None
        """
        dict_attrib = CompuCell.getPyAttrib(cell)

        try:
            sbmlSolver = dict_attrib['SBMLSolver'][model_name]
        except LookupError:
            return

        sbmlSolver.stepSize = step_size
Ejemplo n.º 22
0
    def timestep_model(self, model_name: str):
        """
        Integrate an ode model one step in time.

        :param model_name: name of the ode model
        :return: None
        """
        if model_name not in self.model_names:
            raise ValueError('Model not registered:', model_name)
        o = self._ode_models[model_name]
        if o.cell_types is None:
            from cc3d.CompuCellSetup import persistent_globals as pg
            pg.free_floating_sbml_simulators[model_name].timestep()
        else:
            for cell in self.cell_list_by_type(
                    *self.cell_types_by_model(model_name)):
                dict_attrib = CompuCell.getPyAttrib(cell)
                dict_attrib['SBMLSolver'][model_name].timestep()
Ejemplo n.º 23
0
    def __init__(self, cell_pixel_list, neighbor_order=-1):
        self.boundary_pixel_tracker_accessor = cell_pixel_list.boundary_pixel_tracker_accessor
        self.boundary_pixel_tracker_plugin = cell_pixel_list.boundary_pixel_tracker_plugin
        self.cell = cell_pixel_list.cell
        self.boundary_pixel_itr = CompuCell.boundaryPixelSetPyItr()
        self.boundary_pixel_tracker = self.boundary_pixel_tracker_accessor.get(
            self.cell.extraAttribPtr)
        if neighbor_order <= 0:
            self.pixelSet = self.boundary_pixel_tracker.pixelSet
        else:
            self.pixelSet = self.boundary_pixel_tracker_plugin.getPixelSetForNeighborOrderPtr(
                self.cell, neighbor_order)
            if not self.pixelSet:
                raise LookupError(
                    'LookupError: CellBoundaryPixelIterator could not locate pixel set '
                    'for neighbor order = %s. Make sure your BoundaryPixelTracker plugin definition '
                    'requests tracking of neighbor order =%s boundary' %
                    (neighbor_order, neighbor_order))

        # self.boundaryPixelItr.initialize(self.boundaryPixelTracker.pixelSet)
        self.boundary_pixel_itr.initialize(self.pixelSet)
        self.boundary_pixel_itr.setToBegin()
    def get_sbml_simulator(self, model_name: str, cell: object = None) -> Union[object, None]:
        """
        Returns a reference to RoadRunnerPy or None
        :param model_name: model name
        :param cell: CellG cell object
        :return {instance of RoadRunnerPy} or {None}:
        """

        pg = CompuCellSetup.persistent_globals
        if not cell:
            try:

                return pg.free_floating_sbml_simulators[model_name]

            except LookupError:
                return None
        else:
            try:
                dict_attrib = CompuCell.getPyAttrib(cell)
                return dict_attrib['SBMLSolver'][model_name]
            except LookupError:
                return None
    def delete_sbml_from_cell_types(self, model_name: str, cell_types: Union[None, list] = None) -> None:
        """
        Deletes  SBML model from cells whose type match those stered in the cell_types list
        :param model_name: model name
        :param cell_types: list of cell cell types
        :return:
        """
        """

        :param _modelName {str}: 
        :param types: 
        :return: None

        """
        cell_types = self.__default_mutable_type(cell_types, [])

        for cell in self.cellListByType(*cell_types):
            dict_attrib = CompuCell.getPyAttrib(cell)
            try:
                sbml_dict = dict_attrib['SBMLSolver']
                del sbml_dict[model_name]
            except LookupError:
                pass
Ejemplo n.º 26
0
    def step(self, mcs):
        """
        type here the code that will run every frequency MCS
        :param mcs: current Monte Carlo step
        """
        pt_1 = [10, 11, 4]
        pt_2 = [11, 15, 2]

        pt_hex_1 = self.cartesian_2_hex(pt_1)
        pt_1_cart = self.hex_2_cartesian(pt_hex_1)

        print('pt_1=', pt_1, ' pt_hex_1=', pt_hex_1, ' pt_1_cart=', pt_1_cart)

        pt_hex_2 = self.cartesian_2_hex(pt_2)
        pt_2_cart = self.hex_2_cartesian(pt_hex_2)
        print('pt_2=', pt_2, ' pt_hex_1=', pt_hex_2, ' pt_1_cart=', pt_2_cart)

        pt = CompuCell.Point3D(10, 12, 2)
        pt_np = self.point_3d_to_numpy(pt)

        print('pt=', pt, ' pt_np=', pt_np)

        pt_np = [12, 23, 32]
        pt = self.numpy_to_point_3d(pt_np)

        print('pt=', pt, ' pt_np=', pt_np)

        cell_1 = self.cell_field[30, 30, 0]
        cell_2 = self.cell_field[50, 50, 0]

        cells_different_flag = self.are_cells_different(cell1=cell_1,
                                                        cell2=cell_2)

        print('cell_1=', cell_1, ' cell_2=', cell_2, ' cells_different_flag=',
              cells_different_flag)

        print('self.simulator.getNumSteps() = ', self.simulator.getNumSteps())
Ejemplo n.º 27
0
    def init_fpp_links_actors(self, actor_specs, drawing_params=None):
        """
        initializes fpp links actors
        :param actor_specs:
        :param drawing_params:
        :return: None
        """

        fppPlugin = CompuCell.getFocalPointPlasticityPlugin()
        # if (fppPlugin == 0):  # bogus check
        if not fppPlugin:  # bogus check
            print('    fppPlugin is null, returning')
            return

        actors_dict = actor_specs.actors_dict
        field_dim = self.currentDrawingParameters.bsd.fieldDim
        scene_metadata = drawing_params.screenshot_data.metadata
        mdata = MetadataHandler(mdata=scene_metadata)

        xdim = field_dim.x
        ydim = field_dim.y

        try:
            cellField = self.currentDrawingParameters.bsd.sim.getPotts(
            ).getCellFieldG()
            inventory = self.currentDrawingParameters.bsd.sim.getPotts(
            ).getCellInventory()
        except AttributeError:
            raise AttributeError('Could not access Potts object')

        cellList = CellList(inventory)

        points = vtk.vtkPoints()
        lines = vtk.vtkCellArray()

        beginPt = 0
        lineNum = 0

        for cell in cellList:
            vol = cell.volume
            if vol < self.eps: continue

            xmid0 = cell.xCOM
            ymid0 = cell.yCOM
            zmid0 = cell.zCOM

            points.InsertNextPoint(xmid0, ymid0, zmid0)
            endPt = beginPt + 1

            for fppd in InternalFocalPointPlasticityDataList(fppPlugin, cell):
                xmid = fppd.neighborAddress.xCOM
                ymid = fppd.neighborAddress.yCOM
                zmid = fppd.neighborAddress.zCOM

                xdiff = xmid - xmid0
                ydiff = ymid - ymid0
                zdiff = zmid - zmid0

                actualDist = math.sqrt(xdiff**2 + ydiff**2 + zdiff**2)
                if actualDist > fppd.maxDistance:
                    # implies we have wraparound (via periodic BCs)
                    # we are not drawing those links that wrap around the lattice - leaving the code for now
                    # todo - most likely will redo this part later
                    continue

                    # add dangling "out" line to beginning cell
                    if abs(xdiff) > abs(ydiff):  # wraps around in x-direction
                        if xdiff < 0:
                            xmid0end = xmid0 + self.stubSize
                        else:
                            xmid0end = xmid0 - self.stubSize
                        ymid0end = ymid0
                        points.InsertNextPoint(xmid0end, ymid0end, 0)
                        lines.InsertNextCell(2)  # our line has 2 points
                        lines.InsertCellPoint(beginPt)
                        lines.InsertCellPoint(endPt)

                        actualDist = xdim - actualDist  # compute (approximate) real actualDist
                        lineNum += 1
                        endPt += 1
                    else:  # wraps around in y-direction
                        xmid0end = xmid0
                        if ydiff < 0:
                            ymid0end = ymid0 + self.stubSize
                        else:
                            ymid0end = ymid0 - self.stubSize
                        points.InsertNextPoint(xmid0end, ymid0end, 0)
                        lines.InsertNextCell(2)  # our line has 2 points
                        lines.InsertCellPoint(beginPt)
                        lines.InsertCellPoint(endPt)

                        actualDist = ydim - actualDist  # compute (approximate) real actualDist

                        lineNum += 1

                        endPt += 1

                # link didn't wrap around on lattice
                else:
                    points.InsertNextPoint(xmid, ymid, zmid)
                    lines.InsertNextCell(2)  # our line has 2 points
                    lines.InsertCellPoint(beginPt)
                    lines.InsertCellPoint(endPt)

                    lineNum += 1
                    endPt += 1
            for fppd in FocalPointPlasticityDataList(fppPlugin, cell):

                xmid = fppd.neighborAddress.xCOM
                ymid = fppd.neighborAddress.yCOM
                zmid = fppd.neighborAddress.zCOM

                xdiff = xmid - xmid0
                ydiff = ymid - ymid0
                zdiff = ymid - zmid0

                actualDist = math.sqrt(xdiff**2 + ydiff**2 + zdiff**2)
                if actualDist > fppd.maxDistance:  # implies we have wraparound (via periodic BCs)
                    # we are not drawing those links that wrap around the lattice - leaving the code for now
                    # todo - most likely will redo this part later
                    continue
                    # add dangling "out" line to beginning cell
                    if abs(xdiff) > abs(ydiff):  # wraps around in x-direction
                        #                    print '>>>>>> wraparound X'
                        if xdiff < 0:
                            xmid0end = xmid0 + self.stubSize
                        else:
                            xmid0end = xmid0 - self.stubSize
                        ymid0end = ymid0
                        points.InsertNextPoint(xmid0end, ymid0end, 0)
                        lines.InsertNextCell(2)  # our line has 2 points
                        lines.InsertCellPoint(beginPt)
                        lines.InsertCellPoint(endPt)

                        # coloring the FPP links
                        actualDist = xdim - actualDist  # compute (approximate) real actualDist

                        lineNum += 1

                        endPt += 1
                    else:  # wraps around in y-direction
                        xmid0end = xmid0
                        if ydiff < 0:
                            ymid0end = ymid0 + self.stubSize
                        else:
                            ymid0end = ymid0 - self.stubSize
                        points.InsertNextPoint(xmid0end, ymid0end, 0)
                        lines.InsertNextCell(2)  # our line has 2 points
                        lines.InsertCellPoint(beginPt)
                        lines.InsertCellPoint(endPt)

                        # coloring the FPP links
                        actualDist = ydim - actualDist  # compute (approximate) real actualDist

                        lineNum += 1

                        endPt += 1

                # link didn't wrap around on lattice
                else:
                    points.InsertNextPoint(xmid, ymid, zmid)
                    lines.InsertNextCell(2)  # our line has 2 points
                    lines.InsertCellPoint(beginPt)
                    lines.InsertCellPoint(endPt)

                    lineNum += 1
                    endPt += 1
            beginPt = endPt  # update point index

        # -----------------------
        if lineNum == 0:
            return

        FPPLinksPD = vtk.vtkPolyData()
        FPPLinksPD.SetPoints(points)
        FPPLinksPD.SetLines(lines)

        fpp_links_actor = actors_dict['fpp_links_actor']

        if VTK_MAJOR_VERSION >= 6:
            self.FPPLinksMapper.SetInputData(FPPLinksPD)
        else:
            FPPLinksPD.Update()
            self.FPPLinksMapper.SetInput(FPPLinksPD)

        fpp_links_actor.SetMapper(self.FPPLinksMapper)
        fpp_links_color = to_vtk_rgb(
            mdata.get('FPPLinksColor', data_type='color'))
        # coloring borders
        fpp_links_actor.GetProperty().SetColor(*fpp_links_color)
Ejemplo n.º 28
0
 def start(self):
     self.yes_fluc_comp = CompuCell.getConcentrationField(
         self.simulator, "YesFlucComp")
     self.no_fluc_comp = CompuCell.getConcentrationField(
         self.simulator, "NoFlucComp")
Ejemplo n.º 29
0
 def start(self):
     # initial condition for diffusion field
     field = CompuCell.getConcentrationField(self.simulator, "FGF")
     field[26:28, 26:28, 0:5] = 2000.0
Ejemplo n.º 30
0
    def extract_lattice_description_info(self, file_name: str) -> None:
        """
        Reads the xml that summarizes serialized simulation files
        :param file_name:{str} xml metadata file name
        :return: None
        """

        # lattice data simulation file
        lds_file = os.path.abspath(file_name)
        self.ldsDir = os.path.dirname(lds_file)

        xml2_obj_converter = XMLUtils.Xml2Obj()
        root_element = xml2_obj_converter.Parse(lds_file)
        dim_element = root_element.getFirstElement("Dimensions")
        self.fieldDim = CompuCell.Dim3D()
        self.fieldDim.x = int(dim_element.getAttribute("x"))
        self.fieldDim.y = int(dim_element.getAttribute("y"))
        self.fieldDim.z = int(dim_element.getAttribute("z"))
        output_element = root_element.getFirstElement("Output")
        self.ldsCoreFileName = output_element.getAttribute("CoreFileName")
        self.frequency = int(output_element.getAttribute("Frequency"))
        self.numberOfSteps = int(output_element.getAttribute("NumberOfSteps"))

        # obtaining list of files in the ldsDir
        lattice_element = root_element.getFirstElement("Lattice")
        self.latticeType = lattice_element.getAttribute("Type")

        # getting information about cell type names and cell ids.
        # It is necessary during generation of the PIF files from VTK output
        cell_types_elements = root_element.getElements("CellType")
        list_cell_type_elements = CC3DXMLListPy(cell_types_elements)
        for cell_type_element in list_cell_type_elements:
            type_name = cell_type_element.getAttribute("TypeName")
            type_id = cell_type_element.getAttributeAsInt("TypeId")
            self.typeIdTypeNameDict[type_id] = type_name

        # now will convert python dictionary into C++ map<int, string>

        self.typeIdTypeNameCppMap = CC3DXML.MapIntStr()
        for type_id in list(self.typeIdTypeNameDict.keys()):
            self.typeIdTypeNameCppMap[int(
                type_id)] = self.typeIdTypeNameDict[type_id]

        lds_file_list = os.listdir(self.ldsDir)

        for fName in lds_file_list:
            if re.match(".*\.vtk$", fName):
                self.ldsFileList.append(fName)

        self.ldsFileList.sort()

        # extracting information about fields in the lds file
        fields_element = root_element.getFirstElement("Fields")
        if fields_element:
            field_list = XMLUtils.CC3DXMLListPy(
                fields_element.getElements("Field"))

            for field_elem in field_list:

                field_name = field_elem.getAttribute("Name")
                self.fieldsUsed[field_elem.getAttribute(
                    "Name")] = field_elem.getAttribute("Type")
                if field_elem.findAttribute(
                        "Script"):  # True or False if present
                    # ToDo:  if a "CustomVis" Type was provided,
                    #  require that a "Script" was also provided; else warn user
                    custom_vis_script = field_elem.getAttribute("Script")

                    self.customVis = CompuCellSetup.createCustomVisPy(
                        field_name)
                    self.customVis.registerVisCallbackFunction(
                        CompuCellSetup.vtkScriptCallback)

                    self.customVis.addActor(field_name, "vtkActor")
                    # we'll piggyback off the actorsDict
                    self.customVis.addActor("customVTKScript",
                                            custom_vis_script)