Esempio n. 1
0
    def __init__(self, case_path, graph, **kwargs):
        """
        Constructor

        Args:
            case_path (str): path to current case
            graph (igraph.Graph): directed graph with flow and geometry information
            **topological_radii (bool): whether to use topological tissue radii (default: True)
            **tissue_volumes_file (str): name of the file with the topological tissue volumes
            **average_hb (bool): whether to average the hemoblogin saturation at converging
                                 bifurcations
        """
        self.case_path = case_path
        self.graph = graph
        self.sim_params = SimulationParametersFactory().make_sim_params(
            case_path)
        self.inlet_hb = GraphInletValue.from_json(
            os.path.join(case_path, self.inlet_value_file))
        self.use_topological_radii = kwargs.get('topological_radii', True)
        self.tissue_volumes_results = TissueVolumeResults(case_path)
        self.average_hb = kwargs.get('average_hb', False)
        self.topological_tissue_volumes_dict = \
            {ei: vt for ei, vt in zip(self.tissue_volumes_results.edge_ids(),
                                      self.tissue_volumes_results.topological_tissue_volumes())}
        self.functional_tissue_volumes_dict = \
            {ei: vt for ei, vt in zip(self.tissue_volumes_results.edge_ids(),
                                      self.tissue_volumes_results.functional_tissue_volumes())}
        self.compute()
Esempio n. 2
0
 def __init__(self, case_path, sample_dir_name='sampleRBCHb'):
     super(RBCDataSampled, self).__init__(case_path)
     self.sim_params = SimulationParametersFactory().make_sim_params(
         case_path)
     self.rbc_fields = loadSampledRBCs(case_path,
                                       sample_dir_name,
                                       cache_paths=False)
     self._change_rbc_field_names()
Esempio n. 3
0
def plotPO2SimulatedAndAnalyticalYProfile(caseName, time, x, **kwargs):
    simParams = SimulationParametersFactory().make_sim_params(caseName)
    fieldNames = kwargs.get('fieldNames', ['PO2'])
    plotPO2YProfiles.plotRadialProfile(caseName,
                                       x,
                                       float(time),
                                       fieldNames,
                                       plotFields=['PO2Mean'])
    # plotPO2YProfiles.plotRadialProfileFromPath('PO2RBCAxialAveraged.txt')
    plotPO2ProfileAnalytical.plotPO2YProfile(simParams, x, **kwargs)
Esempio n. 4
0
 def __init__(self, parameterStudyFile='params.json'):
     super(ParameterStudy, self).__init__()
     self['file'] = parameterStudyFile
     jsonData = open(parameterStudyFile)
     self.data = json.load(jsonData)
     jsonData.close()
     self['path'] = os.path.dirname(self['file'])
     self['baseCaseName'] = self.data['baseCase']
     self['baseCasePath'] = os.path.join(self['path'], self['baseCaseName'])
     self.baseCaseSimParams = SimulationParametersFactory().make_sim_params(
         self['baseCasePath'])
    plotter = AxisymmetricCasePlotter(postprocessor)
    plotter.plot_field_average_profile('Hb_mean', n_average=1)


def plotHbSimulatedGraph(caseName):
    postprocessor = GraphCasePostProcessor(caseName)
    plotter = GraphCasePlotter(postprocessor)
    plotter.plotFieldAverageProfile('Hb_mean', 0, nAverage=10)


def plotHbSimulatedAndAnalytical(caseName, simParams, **kwargs):
    if isGraphCase(caseName):
        plotHbSimulatedGraph(caseName)
    elif isAxisymmetricCase(caseName):
        plotHbSimulatedAxisymmetric(caseName)
    plotHbProfile(simParams, **kwargs)
    # plt.legend(['Simulated', 'ODE model'])


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    figOptions = FigureOptions(parser)
    args = parser.parse_args()
    figOptions.parseOptions(args)

    analyticalLineStyle = {'color': 'k', 'linestyle': '-', 'dashes': (4, 2.5)}

    simParams = SimulationParametersFactory().make_sim_params('.')
    plotHbSimulatedAndAnalytical('.', simParams, style=analyticalLineStyle)
    figOptions.saveFig('plotHbSimulatedAndAnalytical')
Esempio n. 6
0
 def __init__(self, case_path):
     self.case_path = case_path
     self.simParams = SimulationParametersFactory().make_sim_params(case_path)
Esempio n. 7
0
class CasePostProcessor(object):
    """
    General post processor for an OpenFOAM case.

    The attributes simParams, rbcData and rbcDataPostProcessor are constructed according to
    the type of OpenFOAM case.

    Results are accessible in string form, based on the class attributes result_output_dict
    which should be redefined by subclasses.

    Attributes:
        case_path (str): path to case to postprocess
        simParams (HbO2Parameters: simulation parameters

    Lazy properties:
        rbc_data (rbc_data): RBC data
        rbcDataPostProcessor (RBCDataPostProcessor)

    Class attributes:
        result_output_dict (OrderedDict): dictionary that defines the postprocessor text output
        output_file_name (str): name of the output file.
    """

    output_file_name = 'results.txt'

    # Dictionary that defines how to extract and display results in the method result_string.
    # The syntax is:
    # dict[headerName] = (methodName, args, formatString), where
    #     headerName (str): name of the header
    #     methodName: (str) method of postprocessor class to call
    #     args (tuple): method arguments
    #     formatString (str): string formatter for output
    result_output_dict = OrderedDict()

    def __init__(self, case_path):
        self.case_path = case_path
        self.simParams = SimulationParametersFactory().make_sim_params(case_path)

    def run(self):
        pass

    def fieldTimeDirs(self):
        """Return the list of time folders where fields have been written."""
        return time_dirs(os.path.join(self.case_path, 'domain'))

    def sValues(self):
        """
        Return the curvilinear coordinates to use on the edge.

        For simulations in graphs, an offset might need to be added to self.xValues.
        """
        if isAxisymmetricCase(self.case_path):
            return self.xValues
        elif isGraphStraightCapillariesCase(self.case_path):
            return self.xValues + self.simParams.sCoordOffset()
        else:
            raise RuntimeError('Case type not supported')

    @lazy_property
    def rbc_data(self):
        return make_rbc_data(self.case_path)

    @lazy_property
    def rbcDataPostProcessor(self):
        if isGraphCase(self.case_path):
            return RBCDataGraphPostProcessor(self.rbc_data)
        elif isAxisymmetricCase(self.case_path):
            return RBCDataPostProcessor(self.rbc_data)

    def result_string(self, result_name, *args, **kwargs):
        """
        Return a string with the a result value.

        The resultName should be a key of the dictionary result_output_dict.

        The method can also be a property of the class. In that case, getattr(self, method)
        does not return a callable object and the value of getattr(self, method) is directly
        used, without using the additional arguments.

        Args:
            result_name (str): name of result to compute
            *args: additional argument to be passed to methods
            **kwargs: dictionary-like arguments to be passed to methods

        Returns:
            string with the result value
        """
        method, firstargs, format_str = self.result_output_dict[result_name]
        if callable(getattr(self, method)):
            result = getattr(self, method)(*(firstargs + args), **kwargs)
        else:
            result = getattr(self, method)
        try:
            return format_str.format(result)
        except ValueError:
            print 'Error with result', result_name, 'while formatting string', \
                  format_str, 'with result', result
            raise

    def output_files_and_result_strings(self, *args, **kwargs):
        """
        Return a dictionary with the output file name as a key and  a list with all strings
        produced by the postprocessor as a value

        Args:
            *args: additional argument to be passed to methods
            **kwargs: dictionary-like arguments to be passed to methods

        Returns:
            dictionary with list of results
        """
        if self.result_output_dict:
            return {self.output_file_name: [self.result_string(result_name, *args, **kwargs)
                                            for result_name in self.result_output_dict.keys()]}
        else:
            return {}

    def output_files_and_result_names(self):
        """
        Return a dictionary with the output file name as a key and  a list with the result names
        as a value

        Returns:
            dictionary with header
        """
        if self.result_output_dict:
            return {self.output_file_name: self.result_output_dict.keys()}
        else:
            return {}
Esempio n. 8
0
    dependentVariables = copy.deepcopy(
        IOHbO2ParametersStraightCapillaries.dependentVariables)
    # no dependent variables are defined in HbO2SimulationParameters
    dependentVariables['CFL'] = ['deltaT']
    dependentVariables['dx'] = ['deltaT']
    dependentVariables['RBCVelocity'] = ['deltaT']

    def __init__(self, case_path='.'):
        super(IOHbO2SimulationParametersStraightCapillaries,
              self).__init__(case_path)


if __name__ == "__main__":
    from HbO2.setup.case import SimulationParametersFactory
    simParams = SimulationParametersFactory().make_sim_params(
        '.', use_numerics=True)
    if isAxisymmetricCase('.'):
        print "Computed deltaT: %g" % simParams['deltaT']
        print simParams
        print "RBC length after setting the radiusRBC to radiusPlasma:"
        simParams['radiusRBC'] = simParams['radiusPlasma']
        print simParams['RBCLength'], simParams['RBCHalfLength']
        print "RBC length after increasing RBC volume:"
        simParams['RBCVolume'] = 69e-18
        print simParams['RBCLength'], simParams['RBCHalfLength']
        simParams.update_files()
    elif isGraphCase('.'):
        print "Computed PO2Tissue: {:g}".format(simParams['PO2Tissue'])
        print "Computed HbInit: {:g}".format(simParams['HbInit'])
        print "Computed deltaT: {:g}".format(simParams['deltaT'])
        simParams.update_files()
Esempio n. 9
0
 def simParamsList(self):
     """Return a list of simulationParameter objects for the parameter study."""
     # return map(lambda s: HbO2SimulationParametersAxisymmetric(s), self.casePaths())
     return map(lambda s: SimulationParametersFactory().\
                          make_sim_params(s, use_numerics=True), self.casePaths())
Esempio n. 10
0
def plotPO2SimulatedAndAnalyticalXProfile(caseName, time, radius, **kwargs):
    simParams = SimulationParametersFactory().make_sim_params(caseName)
    fieldName = kwargs.get('fieldName', 'PO2Mean')
    plotPO2XProfiles.plotPO2ProfileEulerian(caseName, float(time), fieldName)
    plotPO2ProfileAnalytical.plotPO2Profile(simParams, radius, **kwargs)