コード例 #1
0
    def _getColorsForLabels(self):
        self.uniqueLabels = list(
            numpy.array(self.uniqueLabels).reshape(-1,
                                                   self.legendCols).T.reshape(
                                                       -1, 1).ravel())

        self.uniqueColors = [
            PlotTweak.getLabelColor(label) for label in self.uniqueLabels
        ]

        self.labelColors = dict(zip(self.uniqueLabels, self.uniqueColors))

        self.uniqueMathLabels = [
            PlotTweak.getMathLabel(label) for label in self.uniqueLabels
        ]

        self.mathLabelColors = dict(
            zip(self.uniqueMathLabels, self.uniqueColors))
コード例 #2
0
ファイル: Plot.py プロジェクト: JaakkoAhola/LES-03plotting
    def getColorBar(im, ax, levels=None):
        cb = matplotlib.pyplot.colorbar(im,
                                        cax=ax,
                                        ticks=levels,
                                        orientation='horizontal')  #, pad=0.21
        if levels is not None:
            cb.ax.set_xticklabels(
                [r"$10^{" + str(int(elem)) + "}$" for elem in levels])

            colorbarLabelListShowBoolean = Data.getIntegerExponentsAsBoolean(
                levels)
            cb = PlotTweak.hideColorbarXLabels(cb,
                                               colorbarLabelListShowBoolean)
コード例 #3
0
    def _initReadFeatureImportanceData_phase01(self):

        self.featureImportanceDataCollection = {}
        self.allLabels = []
        self.legendCols = 4
        for trainingSet in self.trainingSetList:
            self.featureImportanceDataCollection[trainingSet] = {}
            try:
                dataset = pandas.read_csv(
                    self.postProsDataRootFolder / trainingSet /
                    (trainingSet + "_featureImportance.csv"),
                    index_col=0)
            except FileNotFoundError:
                self.featureImportanceDataCollection[trainingSet] = None
                continue
            for ind in dataset.index:
                series = dataset.loc[ind]
                mean = series.loc[[
                    kk for kk in series.index if kk[-4:] == "Mean"
                ]]
                std = series.loc[[
                    kk for kk in series.index if kk[-4:] == "Mean"
                ]]
                ines = [kk[:-22] for kk in series.index if kk[-4:] == "Mean"]

                self.allLabels += ines

                subset = pandas.DataFrame(data={
                    "Mean": mean.values,
                    "Std": std.values
                },
                                          index=ines).dropna()

                subset["mathLabel"] = subset.apply(
                    lambda row: PlotTweak.getMathLabel(row.name), axis=1)

                subset = subset.sort_values("Mean", ascending=False)
                subset["points"] = range(len(subset))
                summa = subset["Mean"].sum()

                subset["relativeImportance"] = subset.apply(
                    lambda row: max(row["Mean"], 0) / summa, axis=1)

                self.featureImportanceDataCollection[trainingSet][ind] = subset

        self.uniqueLabels = list(set(self.allLabels))
コード例 #4
0
    def _initReadFeatureImportanceData_phase04(self):
        relativeCombined = pandas.DataFrame.from_dict(
            self.labelRelative, orient="index", columns=["relativeCombined"])
        zeros = pandas.DataFrame.from_dict(self.zeros,
                                           orient="index",
                                           columns=["zeros"])
        labelOrder = pandas.concat((relativeCombined, zeros), axis=1)

        self.labelRelative = []
        self.labelCategorised = []
        for zeroAmount in set(labelOrder["zeros"].values):
            subdf = labelOrder[labelOrder["zeros"] == zeroAmount].sort_values(
                by="relativeCombined", ascending=False)
            self.labelCategorised.append(subdf)
            self.labelRelative += list(subdf.index.values)

        self.labelCategorised = pandas.concat(self.labelCategorised)

        self.labelCategorised["mathLabel"] = self.labelCategorised.apply(
            lambda row: PlotTweak.getMathLabel(row.name), axis=1)
コード例 #5
0
    def figureDesignVariables(self):
        nrows = 4
        ncols = ceil(len(self.designVariablePool) / nrows)

        self.figures["figureDesignVariables"] = Figure(
            self.figureFolder,
            "figureDesignVariables",
            figsize=[self.figureWidth, 7],
            ncols=ncols,
            nrows=nrows,
            bottom=0.04,
            hspace=0.17,
            wspace=0.07,
            top=0.98,
            left=0.02,
            right=0.98)
        fig = self.figures["figureDesignVariables"]
        rightUp = [0.57, 0.70]
        leftUp = [0.25, 0.73]
        leftDown = [0.1, 0]
        rightDown = [0.45, 0.05]
        middleDown = [0.33, 0.05]
        default = [0.5, 0.5]
        specsPositions = [[0.3, 0.05], [0.2, 0.05], [0.3, 0.5], [0.3, 0.5],
                          [0.3, 0.4], [0.3, 0.5], [0.05, 0.50], [0.05, 0.50],
                          [0.05, 0.50], [0.3, 0.05], middleDown]
        meanStr = "\mu"
        stdStr = "\sigma"

        logVariables = ["ks", "as", "cs", "rdry_AS_eff"]
        for ind, variable in enumerate(self.designVariablePool):
            ax = fig.getAxes(ind)

            minimi = numpy.nan
            maximi = numpy.nan
            if variable == "pblh":
                variableSourceName = "pbl"
            else:
                variableSourceName = variable

            if hasattr(self, "filteredSourceData") and (self.filteredSourceData
                                                        is not None):
                sourceDataVariable = self.filteredSourceData[
                    variableSourceName]
                sourceDataVariable = Data.dropInfNanFromDataFrame(
                    sourceDataVariable)
                if variable in logVariables:
                    sourceDataVariable = numpy.log10(sourceDataVariable)
                sourceDataVariable = Data.dropInfNanFromDataFrame(
                    sourceDataVariable)

                if variable == "cos_mu":
                    sourceDataVariable = sourceDataVariable[
                        sourceDataVariable > Data.getEpsilon()]
                sourceDataVariable.plot.density(
                    ax=ax, color=Colorful.getDistinctColorList("grey"))

                variableSpecs = f"""{PlotTweak.getLatexLabel(f'min={sourceDataVariable.min():.2f}')}
{PlotTweak.getLatexLabel(f'{meanStr}={sourceDataVariable.mean():.2f}')}
{PlotTweak.getLatexLabel(f'{stdStr}={sourceDataVariable.std():.2f}')}
{PlotTweak.getLatexLabel(f'max={sourceDataVariable.max():.2f}')}"""

                ax.annotate(variableSpecs,
                            xy=specsPositions[ind],
                            size=8,
                            bbox=dict(pad=0.6, fc="w", ec="w", alpha=0.9),
                            xycoords="axes fraction")

            isAnnotated = True
            for tt, trainingSet in enumerate(self.trainingSetList):

                if variable in self.completeDataFrame[trainingSet].keys():

                    if self.completeDataFrame[trainingSet] is None:
                        continue

                    trainingSetVariable = self.completeDataFrame[trainingSet][
                        variable]
                    if variable in logVariables:
                        loga = PlotTweak.getLatexLabel("log_{10} ")
                        trainingSetVariable = numpy.log10(trainingSetVariable)
                        trainingSetVariable = Data.dropInfNanFromDataFrame(
                            trainingSetVariable)
                    else:
                        loga = ""

                    minimi = numpy.nanmin([minimi, trainingSetVariable.min()])
                    maximi = numpy.nanmax([maximi, trainingSetVariable.max()])
                    trainingSetVariable.plot.density(
                        ax=ax, color=self.trainingSetColors[trainingSet])

                    variableSpecs = f"""{PlotTweak.getLatexLabel(f'min={trainingSetVariable.min():.2f}')}
{PlotTweak.getLatexLabel(f'{meanStr}={trainingSetVariable.mean():.2f}')}
{PlotTweak.getLatexLabel(f'{stdStr}={trainingSetVariable.std():.2f}')}
{PlotTweak.getLatexLabel(f'max={trainingSetVariable.max():.2f}')}"""

                    if not hasattr(self, "filteredSourceData") and isAnnotated:
                        ax.annotate(variableSpecs,
                                    xy=specsPositions[ind],
                                    size=8,
                                    bbox=dict(pad=0.6,
                                              fc="w",
                                              ec="w",
                                              alpha=0.9),
                                    xycoords="axes fraction")
                        isAnnotated = False

            annotation = f"({Data.getNthLetter(ind)}) {loga}{PlotTweak.getMathLabel(variable)}"
            PlotTweak.setAnnotation(ax,
                                    annotation,
                                    xPosition=0.05,
                                    yPosition=0.9,
                                    xycoords="axes fraction")
            ax.set_ylabel("")
            ax.set_xlim([minimi, maximi])
            PlotTweak.hideYTickLabels(ax)

        ax = fig.getAxes(11)
        ax.axis("off")

        legendLabelColors = PlotTweak.getPatches(self.allSetColors)

        artist = ax.legend(handles=legendLabelColors,
                           loc=(0.0, 0.00),
                           frameon=True,
                           framealpha=1.0,
                           ncol=1)

        ax.add_artist(artist)
コード例 #6
0
    def __figureUpdraft_vs_CloudRadiativeWarming(self, updraftVariableName,
                                                 names: dict, dataColor):

        self.figures[names["fig"]] = Figure(self.figureFolder,
                                            names["fig"],
                                            figsize=[self.figureWidth, 4],
                                            ncols=2,
                                            nrows=2,
                                            bottom=0.11,
                                            hspace=0.08,
                                            wspace=0.12,
                                            top=0.94)
        fig = self.figures[names["fig"]]

        xstart = -140
        xend = 50

        ystart = 0.0
        yend = 1.0
        yticks = numpy.arange(0, yend + .01, 0.1)
        tickLabels = [f"{t:.1f}" for t in yticks]

        yShowList = Data.cycleBoolean(len(yticks))

        color_obs = Colorful.getDistinctColorList("grey")
        condition = {}
        for ind, trainingSet in enumerate(self.trainingSetList):
            ax = fig.getAxes(ind)

            dataframe = self.completeDataFrameFiltered[trainingSet]

            if dataframe is None:
                continue

            condition["notMatchObservation"] = ~ ( (dataframe[updraftVariableName] > dataframe["drflx"]*self.observationParameters["slope"]+ self.observationParameters["intercept"]-self.observationParameters["error"]) &\
                                                   (dataframe[updraftVariableName] < dataframe["drflx"]*self.observationParameters["slope"]+ self.observationParameters["intercept"]+self.observationParameters["error"]))

            dataFrameInside = dataframe[~condition["notMatchObservation"]]
            percentageInside = len(dataFrameInside) / len(dataframe) * 100.

            radiativeWarming = dataframe["drflx"].values
            updraft = dataframe[updraftVariableName].values

            poly1d_Observation = numpy.poly1d(
                numpy.asarray([
                    self.observationParameters["slope"],
                    self.observationParameters["intercept"]
                ]))  #?0.44 ×CTRC+
            ax.plot(radiativeWarming,
                    poly1d_Observation(radiativeWarming),
                    color=color_obs)
            ax.fill_between(sorted(radiativeWarming),
                            poly1d_Observation(sorted(radiativeWarming)) -
                            self.observationParameters["error"] *
                            numpy.ones(numpy.shape(radiativeWarming)),
                            poly1d_Observation(sorted(radiativeWarming)) +
                            self.observationParameters["error"] *
                            numpy.ones(numpy.shape(radiativeWarming)),
                            alpha=0.2)

            slope, intercept, r_value, p_value, std_err = stats.linregress(
                radiativeWarming, updraft)
            coef = [slope, intercept]
            rSquared = numpy.power(r_value, 2)

            fitColor = "k"
            dataframe.plot.scatter(ax=ax,
                                   x="drflx",
                                   y=updraftVariableName,
                                   alpha=0.3,
                                   color=dataColor)

            poly1d_fn = numpy.poly1d(coef)

            linearFit = []
            for radWarmingValue in list(
                    self.completeDataFrame[trainingSet]["drflx"]):
                linearFit.append(poly1d_fn(radWarmingValue))

            self.completeDataFrame[trainingSet][
                self.linearFitVariable] = linearFit
            ax.plot(radiativeWarming,
                    poly1d_fn(radiativeWarming),
                    color=fitColor)

            ax.set_xlim([xstart, xend])
            ax.set_ylim([ystart, yend])

            PlotTweak.setAnnotation(ax,
                                    self.annotationCollection[trainingSet],
                                    xPosition=PlotTweak.getXPosition(ax, 0.02),
                                    yPosition=PlotTweak.getYPosition(ax, 0.93))

            PlotTweak.setXaxisLabel(ax, "")
            PlotTweak.setYaxisLabel(ax, "")

            xticks = PlotTweak.setXticks(ax,
                                         start=xstart,
                                         end=xend,
                                         interval=10,
                                         integer=True)

            xShownLabelsBoolean = PlotTweak.setXLabels(ax,
                                                       xticks,
                                                       start=xstart,
                                                       end=xend,
                                                       interval=40)
            xShownLabelsBoolean = Data.cycleBoolean(len(xShownLabelsBoolean))
            PlotTweak.setXTickSizes(ax, xShownLabelsBoolean)

            if ind == 0:
                collectionOfLabelsColors = {
                    names["legend"]: dataColor,
                    "Fit": "k",
                    "Observations": color_obs
                }
                legendLabelColors = PlotTweak.getPatches(
                    collectionOfLabelsColors)

                artist = ax.legend(handles=legendLabelColors,
                                   loc=(0.17, 1.02),
                                   frameon=True,
                                   framealpha=1.0,
                                   ncol=3)

                ax.add_artist(artist)

            ax.text(-25,
                    0.67,
                    f"""{PlotTweak.getLatexLabel('y=a + b * x')}
{PlotTweak.getLatexLabel(f'a={intercept:.4f}')}
{PlotTweak.getLatexLabel(f'b={slope:.6f}')}
{PlotTweak.getLatexLabel(f'R^2={rSquared:.2f}')}
{PlotTweak.getLatexLabel('p_{in}=' + f'{percentageInside:.1f}')}%""",
                    fontsize=6)

            ax.set_yticks(yticks)
            ax.set_yticklabels(tickLabels)
            PlotTweak.setYTickSizes(ax, yShowList)
            PlotTweak.hideLabels(ax.yaxis, yShowList)

            if ind in [1, 3]:
                PlotTweak.hideYTickLabels(ax)

            if ind in [0, 1]:
                PlotTweak.hideXTickLabels(ax)
            if ind == 0:
                ax.text(PlotTweak.getXPosition(ax, -0.27),
                        PlotTweak.getYPosition(ax, -0.5),
                        PlotTweak.getUnitLabel(names["legend"] + "\ w_{pos}",
                                               "m\ s^{-1}"),
                        size=8,
                        rotation=90)
            if ind == 2:
                ax.text(0.3,
                        -0.25,
                        PlotTweak.getUnitLabel("Cloud\ rad.\ warming",
                                               "W\ m^{-2}"),
                        size=8)
コード例 #7
0
    def figurePredictorsVsSimulated(self):
        numberOfMethods = 3
        self.figures["figurePredictorsVsSimulated"] = Figure(
            self.figureFolder,
            "figurePredictorsVsSimulated",
            figsize=[self.figureWidth, 7],
            ncols=numberOfMethods,
            nrows=4,
            bottom=0.07,
            hspace=0.09,
            wspace=0.10,
            top=0.95,
            left=0.16,
            right=0.98)
        fig = self.figures["figurePredictorsVsSimulated"]

        start = 0.0
        end = 1.0
        ticks = numpy.arange(0, end + .01, 0.1)
        tickLabels = [f"{t:.1f}" for t in ticks]

        showList = Data.cycleBoolean(len(ticks))

        showList[0] = False
        showList[-1] = False

        for row, trainingSet in enumerate(self.trainingSetList):
            for col, predictor in enumerate(self.predictionVariableList):
                ax = fig.getAxesGridPoint({"row": row, "col": col})
                shortname = self.predictorShortNames[col]
                dataframe = self.completeDataFrame[trainingSet]
                if self.completeDataFrame[
                        trainingSet] is None or self.statsCollection[
                            trainingSet] is None:
                    continue

                dataframe = dataframe.loc[dataframe[self.filterIndex]]

                simulated = dataframe[self.responseVariable]

                statistics = self.statsCollection[trainingSet].loc[
                    self.predictorShortNames[col]]

                slope = statistics["slope"]
                intercept = statistics["intercept"]
                rSquared = statistics["rSquared"]
                rmse = statistics["rmse"]

                dataframe.plot.scatter(ax=ax,
                                       x=self.responseVariable,
                                       y=predictor,
                                       color=self.predictorColors[shortname],
                                       alpha=0.3)

                coef = [slope, intercept]
                poly1d_fn = numpy.poly1d(coef)
                ax.plot(simulated.values,
                        poly1d_fn(simulated.values),
                        color="k")

                ax.set_ylim([start, end])

                ax.set_xlim([start, end])

                PlotTweak.setAnnotation(
                    ax,
                    f"""{PlotTweak.getLatexLabel(f'R^2={rSquared:.2f}','')}
{PlotTweak.getLatexLabel(f'RMSE={rmse:.3f}','')}""",
                    xPosition=0.28,
                    yPosition=0.05,
                    bbox_props=None)

                PlotTweak.setXaxisLabel(ax, "")
                PlotTweak.setYaxisLabel(ax, "")

                ax.set_xticks(ticks)
                ax.set_xticklabels(tickLabels)
                PlotTweak.hideLabels(ax.xaxis, showList)

                ax.set_yticks(ticks)
                ax.set_yticklabels(tickLabels)
                PlotTweak.hideLabels(ax.yaxis, showList)

                PlotTweak.setXTickSizes(ax, Data.cycleBoolean(len(ticks)))
                PlotTweak.setYTickSizes(ax, Data.cycleBoolean(len(ticks)))

        for ind in range(12):
            ax = fig.getAxes(ind)

            PlotTweak.setAnnotation(ax,
                                    f"({Data.getNthLetter(ind)})",
                                    xPosition=ax.get_xlim()[1] * 0.05,
                                    yPosition=ax.get_ylim()[1] * 0.90)

            if ind not in numpy.asarray(range(4)) * 3:
                PlotTweak.hideYTickLabels(ax)
            else:
                ax.text(PlotTweak.getXPosition(ax, -0.56),
                        PlotTweak.getYPosition(ax, 0.3),
                        PlotTweak.getLatexLabel(
                            self.trainingSetSensibleNames[ind // 3]),
                        size=8,
                        rotation=90)

            if ind not in list(range(9, 12)):
                PlotTweak.hideXTickLabels(ax)

            if ind == 0:
                collectionOfLabelsColors = dict(
                    zip(list(self.predictorClearNames.values()),
                        list(self.predictorColors.values())))
                legendLabelColors = PlotTweak.getPatches(
                    collectionOfLabelsColors)

                artist = ax.legend(handles=legendLabelColors,
                                   loc=(-0.52, 1.05),
                                   frameon=True,
                                   framealpha=1.0,
                                   ncol=3)

                ax.add_artist(artist)

            if ind == 3:
                ax.text(PlotTweak.getXPosition(ax, -0.42),
                        PlotTweak.getYPosition(ax, -0.5),
                        PlotTweak.getUnitLabel("Predicted\ w_{pos}",
                                               "m\ s^{-1}"),
                        size=8,
                        rotation=90)
            if ind == 10:
                ax.text(-0.1,
                        -0.27,
                        PlotTweak.getUnitLabel("Simulated\ w_{pos}",
                                               "m\ s^{-1}"),
                        size=8)
コード例 #8
0
    def __init__(self, locationsFile):

        super().__init__(locationsFile)

        self.figures = {}

        self.figureWidth = 12 / 2.54

        self.trainingSetList = ["LVL3Night", "LVL3Day", "LVL4Night", "LVL4Day"]

        self.trainingSetColors = dict(
            zip(
                self.trainingSetList,
                Colorful.getDistinctColorList(
                    ["blue", "cyan", "red", "orange"])))

        self.figureFolder.mkdir(parents=True, exist_ok=True)

        self.tableFolder.mkdir(parents=True, exist_ok=True)

        self.annotationValues = [
            "(a) SB Night", "(b) SB Day", "(c) SALSA Night", "(d) SALSA Day"
        ]

        self.trainingSetSensibleNames = [
            "SB\ Night", "SB\ Day", "SALSA\ Night", "SALSA\ Day"
        ]

        self.trainingSetSensibleDict = dict(
            zip(self.trainingSetList, self.trainingSetSensibleNames))

        self.allSetColors = dict(
            zip([
                PlotTweak.getLatexLabel(name)
                for name in ["Filtered\ ECHAM"] + self.trainingSetSensibleNames
            ], [Colorful.getDistinctColorList("grey")] +
                list(self.trainingSetColors.values())))

        self.annotationCollection = dict(
            zip(self.trainingSetList, self.annotationValues))

        self.cloudTopColor = Colorful.getDistinctColorList("green")
        self.lwpColor = Colorful.getDistinctColorList("blue")
        self.tempColor = Colorful.getDistinctColorList("yellow")

        self.observationParameters = {}
        self.observationParameters["slope"] = -0.44 / 100.
        self.observationParameters["intercept"] = 22.30 / 100.
        self.observationParameters["error"] = 13. / 100.

        self.predictorShortNames = [
            "linearFit", "correctedLinearFit", "emulator"
        ]

        self.predictorShortNameDict = dict(
            zip(self.predictionVariableList, self.predictorShortNames))

        self.predictorColors = dict(
            zip(self.predictorShortNames,
                Colorful.getDistinctColorList(["red", "green", "blue"])))

        self.predictorClearNames = dict(
            zip(self.predictorShortNames,
                ["Lin. Fit", "Lin. Fit + Random Forest", "Gaussian Process"]))

        self._initReadCompleteData()

        self._filterCompleteData()

        self._initReadStats()

        self._initReadLimits()

        self._initBootstraps()
コード例 #9
0
    def figureBarFeatureImportanceData(self):
        ncols = len(self.featureImportanceDataCollection[list(
            self.featureImportanceDataCollection)[0]])  # number of methods
        nrows = len(
            self.featureImportanceDataCollection)  # = number of training sets

        self.figures["figureFeatureImportanceBar"] = Figure(
            self.figureFolder,
            "figureFeatureImportanceBar",
            figsize=[self.figureWidth, 6],
            ncols=ncols,
            nrows=nrows,
            hspace=0.8,
            bottom=0.20,
            wspace=0.05,
            top=0.97)
        fig = self.figures["figureFeatureImportanceBar"]

        maksimi = 0
        column = "relativeImportance"
        for row, trainingSet in enumerate(
                list(self.featureImportanceDataCollection)):
            if self.featureImportanceDataCollection[trainingSet] is None:
                continue
            for col, predictor in enumerate(
                    list(self.featureImportanceDataCollection[trainingSet])
                [::-1]):

                dataframe = self.featureImportanceDataCollection[trainingSet][
                    predictor]

                maksimi = max(dataframe[column].max(), maksimi)
                ax = fig.getAxesGridPoint({"row": row, "col": col})

                dataframe.plot(ax=ax,
                               kind="bar",
                               color=dataframe["color"],
                               x="mathLabel",
                               y=column,
                               legend=False)

        for ind in range(nrows * ncols):
            ax = fig.getAxes(ind)

            ymax = round(maksimi, 1) + 0.11
            yTicks = numpy.arange(0, ymax, 0.1)
            yTickLabels = [f"{t:.1f}" for t in yTicks]
            showList = Data.cycleBoolean(len(yTicks))
            ax.set_yticks(yTicks)
            ax.set_yticklabels(yTickLabels)
            ax.set_ylim([0, ymax])
            PlotTweak.hideLabels(ax.yaxis, showList)

            PlotTweak.setXaxisLabel(ax, "")

            PlotTweak.setAnnotation(ax,
                                    f"({Data.getNthLetter(ind)})",
                                    xPosition=ax.get_xlim()[1] * 0.07,
                                    yPosition=ax.get_ylim()[1] * 0.80)

            if ind not in numpy.asarray(range(nrows)) * ncols:
                PlotTweak.hideYTickLabels(ax)
            else:
                ax.text(PlotTweak.getXPosition(ax, -0.24),
                        PlotTweak.getYPosition(ax, 0.),
                        PlotTweak.getLatexLabel(
                            self.trainingSetSensibleNames[ind // ncols]),
                        size=8,
                        rotation=90)
            if ind == 1:
                ax.text(PlotTweak.getXPosition(ax, 0.2),
                        PlotTweak.getYPosition(ax, 1.05),
                        self.predictorClearNames["emulator"],
                        size=8)
            if ind == 0:
                ax.text(PlotTweak.getXPosition(ax, 0.2),
                        PlotTweak.getYPosition(ax, 1.05),
                        self.predictorClearNames["correctedLinearFit"],
                        size=8)

        fig.getAxes(-1).legend(handles=PlotTweak.getPatches(
            self.mathLabelColors),
                               loc=(-0.9, -1.59),
                               ncol=self.legendCols,
                               fontsize=8)
コード例 #10
0
    def figure6(self):
        packing = 4
        xstart = 2.1
        xend = 33.0
        yend = 1.5

        simulation = "Prognostic_48h"
        simulCol = self.simulationCollection[simulation]
        simulCol.getPSDataset()
        simulCol.setTimeCoordToHours()

        simulCol.sliceByTimePSDataset(xstart, xend)

        fig = Figure(self.figurefolder,"figure6", ncols = 2, nrows = 2,
                     hspace=0.1, bottom = 0.10, left=0.05, top=0.93, wspace = 0.06, right=0.99, figsize = [12/2.54, 4])

        aeroAnalysis  = SimulationDataAnalysis( simulCol, "P_Nabb")
        cloudAnalysis = SimulationDataAnalysis( simulCol, "P_Ncbb")
        iceAnalysis   = SimulationDataAnalysis( simulCol, "P_Nibb")

        aeroAnalysis.filterPSVariableInCloud()
        cloudAnalysis.filterPSVariableInCloud()
        iceAnalysis.filterPSVariableInCloud()

        aeroAnalysis.renamePSCoordSizeBinB()
        cloudAnalysis.renamePSCoordSizeBinB()
        iceAnalysis.renamePSCoordSizeBinB()

        aeroAnalysis.packFilteredPSVariablewithSizeBinCoords(packing)
        cloudAnalysis.packFilteredPSVariablewithSizeBinCoords(packing)
        iceAnalysis.packFilteredPSVariablewithSizeBinCoords(packing)

        aero = simulCol.getPSDataset()[aeroAnalysis.getFilteredPackedVariableName()]
        cloud = simulCol.getPSDataset()[cloudAnalysis.getFilteredPackedVariableName()]
        ice = simulCol.getPSDataset()[iceAnalysis.getFilteredPackedVariableName()]

        total = aero + cloud + ice

        aeroColor = Colorful.getDistinctColorList("red")
        cloudColor = Colorful.getDistinctColorList("navy")
        iceColor = Colorful.getDistinctColorList("cyan")
        totalColor = Colorful.getDistinctColorList("green")

        yticks = [0, 0.5, 1, 1.5]


        figName = ["a)", "b)", "c)", "d)"]

        for bini in range(packing):
            ax = fig.getAxes(bini)

            aeroBin = aero[:,bini]
            cloudBin = cloud[:,bini]
            iceBin = ice[:,bini]

            totalBin = total[:,bini]

            aeroFrac = aeroBin/totalBin
            cloudFrac = cloudBin/totalBin
            iceFrac = iceBin/totalBin

            pointZero = totalBin.sel(time = xstart, method ="nearest")

            pointEnd = totalBin.sel(time = xend, method ="nearest").values

            totalBinRelative  = totalBin / pointZero

            totalBinRelative.plot(ax = ax, color = totalColor)
            cloudFrac.plot(ax=ax, color = cloudColor)
            aeroFrac.plot(ax=ax, color = aeroColor)
            iceFrac.plot(ax=ax, color = iceColor)


            if bini == (packing - 1):
                bininame = str(bini + 1 ) + " - 7"
            else:
                bininame = str(bini +1)

            if True:

                label = " ".join([figName[bini], "Bin", bininame + ",", "Total", r"$N_0$",  str(int(pointZero)) + ",", "\nMin", r"$N$", str(int(pointEnd)), "$(kg^{-1})$"  ])
                facecolor = totalColor

                PlotTweak.setArtist(ax, {label:facecolor}, loc = (0.01, 0.74), framealpha = 0.8)

                if bini == 0:
                    collectionOfLabelsColors = {"Aerosol": aeroColor, "Cloud": cloudColor, "Ice": iceColor}
                    PlotTweak.setArtist(ax, collectionOfLabelsColors, ncol = 3, loc = (0.47,1.02))

            ##############
            ax.set_title("")
            PlotTweak.setXLim(ax, start = xstart, end = xend)
            PlotTweak.setYLim(ax, end = yend)

            PlotTweak.setYticks(ax, yticks)
            yShownLabelsBoolean = PlotTweak.setYLabels(ax, yticks, end = 1, interval = 1, integer=False)
            PlotTweak.setYTickSizes(ax, yShownLabelsBoolean)

            xticks = PlotTweak.setXticks(ax, start = xstart, end = xend, interval = 1)
            shownLabelsBoolean = PlotTweak.setXLabels(ax, xticks, end = xend, interval = 4)
            PlotTweak.setXTickSizes(ax, shownLabelsBoolean)

            PlotTweak.setYaxisLabel(ax,"")
            if bini in [2,3]:
                PlotTweak.setXaxisLabel(ax,"Time", "h")
            else:
                PlotTweak.setXaxisLabel(ax,"")
                PlotTweak.hideXTickLabels(ax)

            if bini in [1,3]:
                PlotTweak.hideYTickLabels(ax)
            ###########

        fig.save()
コード例 #11
0
                                        loppu,
                                        marker="o",
                                        markerfacecolor=color,
                                        markeredgecolor="black",
                                        markeredgewidth=0.2,
                                        markersize=6,
                                        alpha=0.5,
                                        zorder=zorderParam)
    print("minimi", mini, "maksimi", maks)

    for ind, case in enumerate(caseCollection):
        PlotTweak.setAnnotation(fig.getAxes(True)[ind],
                                annotationCollection[case],
                                xPosition=100,
                                yPosition=ymax - yPositionCorrection)
        PlotTweak.setXLim(fig.getAxes(True)[ind], 0, xmax)
        PlotTweak.setYLim(fig.getAxes(True)[ind], 0, ymax)
        fig.getAxes(True)[ind].plot([0, xmax], [0, ymax],
                                    'k-',
                                    alpha=0.75,
                                    zorder=0)

    PlotTweak.setXaxisLabel(fig.getAxes(True)[2],
                            xAxisLabel,
                            xAxisUnit,
                            useBold=True)
    PlotTweak.setXaxisLabel(fig.getAxes(True)[3],
                            xAxisLabel,
                            xAxisUnit,
                            useBold=True)
    PlotTweak.setYaxisLabel(fig.getAxes(True)[0],
コード例 #12
0
ファイル: Plot.py プロジェクト: JaakkoAhola/LES-03plotting
    def getTimeseriesOfProportions(
            axes,
            simulation: Simulation,
            muuttuja,
            mode="inCloud",
            cmap="bright",
            limit=1e-6,
            height=None,
            packing=None,
            timeStartH=2.05,
            timeEndH=48,
            analysis=False,
            fontsize=None,
            useLegend=True,
            figurePrefix="",
            kuvakansio="/home/aholaj/OneDrive/000_WORK/000_ARTIKKELIT/000-Manuscript-ICE/kuvat/bini/",
            kuvakansioPDF="/home/aholaj/OneDrive/000_WORK/000_ARTIKKELIT/000-Manuscript-ICE/figures_pdf",
            filenamePDF="figure6"):

        print(mode, end=" ")
        if height is not None:
            print(height)
        else:
            print()

        ps = simulation.getPSDataset()
        if ps is None:
            return "FileNotFound"

        ts = simulation.getTSDataset()
        if ts is None:
            return "FileNotFound"

        timeStartInd = Data.getClosestIndex(ps.time.values, timeStartH * 3600)
        timeEndInd = Data.getClosestIndex(ps.time.values, timeEndH * 3600)
        ps = ps.isel(time=slice(timeStartInd, timeEndInd))

        try:

            if mode == "inCloud":
                # ps = ps.sel(zt = slice(665,745)).mean(dim = "zt")
                ps = ps.where(
                    (ps.P_rl > limit) & (ps.P_ri > limit), drop=True
                ).mean(
                    dim="zt", skipna=True
                )  #ps.where(ps.zt > ts.zb).where(ps.zt < ts.zc).mean(dim = "zt")#
            elif mode == "belowCloud":
                #ps = ps.sel(zt = slice(5,410)).mean(dim = "zt")
                ps = ps.where(ps.P_rl < limit, drop=True).where(
                    ps.zt < ts.zb, drop=True).mean(
                        dim="zt",
                        skipna=True)  #.where(ps.P_rl < 1e-6, drop = True)
            elif mode == "aboveCloud":
                ps = ps.where(ps.zt > ts.zc, drop=True).mean(
                    dim="zt",
                    skipna=True)  #.where(ps.P_rl < 1e-6, drop = True)
            elif mode == "height":
                ps = ps.sel(zt=height, method='nearest')
        except KeyError:
            return

        ps = ps.assign_coords(time=(ps.time / 3600))

        try:
            aero = ps["P_Nabb"]
            cloud = ps["P_Ncbb"]
            ice = ps["P_Nibb"]
        except KeyError:
            return

        newname = "dryRadiusBinB"
        aero = aero.rename({"aeb": newname})
        cloud = cloud.rename({"clb": newname})
        ice = ice.rename({"icb": newname})

        total = aero + cloud + ice

        if packing is not None:
            for daatta in aero, cloud, ice, total:
                daatta[:, packing] = numpy.sum(daatta[:, packing:], axis=1)

        binNumber = min(numpy.shape(total.values)[1], packing + 1)

        matplotlib.rcParams['lines.linewidth'] = 6
        yTicks = [0, 0.5, 1]
        yTickLabels = map(str, yTicks)

        matplotlib.pyplot.subplots_adjust(hspace=0.05, wspace=0.05)

        xLabelListShow = numpy.arange(8, 48 + 1, 8)
        xLabelListShow = numpy.insert(xLabelListShow, 0, 2)

        xLabelListMajorLine = numpy.arange(4, 48 + 1, 4)
        xLabelListMajorLine = numpy.insert(xLabelListMajorLine, 0, 2)

        for bini in range(binNumber):
            ax = axes[bini]
            aeroBin = aero[:, bini]
            cloudBin = cloud[:, bini]
            iceBin = ice[:, bini]

            totalBin = total[:, bini]

            aeroFrac = aeroBin / totalBin
            cloudFrac = cloudBin / totalBin
            iceFrac = iceBin / totalBin

            totalBinRelative = totalBin / totalBin.values[0]

            aeroFrac.plot(ax=ax, color="#e6194B")
            cloudFrac.plot(ax=ax, color="#000075")
            iceFrac.plot(ax=ax, color="#42d4f4")
            totalBinRelative.plot(ax=ax, color="black")

            ax.set_yticks(yTicks)
            ax.set_yticklabels(yTickLabels)
            ax.set_ylim(0, 1.5)
            ax.set_title("")
            matplotlib.pyplot.setp(ax.get_yticklabels()[1], visible=False)

            if packing is not None and bini == (binNumber - 1):
                bininame = str(bini + 1) + " - 7"
            else:
                bininame = str(bini + 1)

            if useLegend:
                legend_handles = [
                    matplotlib.patches.Patch(
                        facecolor="black",
                        label=" ".join([
                            "Bin", bininame + ",", "Total", r"$N_0$",
                            str(int(totalBin.values[0])) + ",", "Min", r"$N$",
                            str(int(numpy.min(totalBin))), "$(kg^{-1})$"
                        ]))
                ]
                legend = ax.legend(handles=legend_handles,
                                   loc="best",
                                   fontsize=fontsize)
                ax.add_artist(legend)

                if bini == 0:
                    header_handles = [
                        matplotlib.patches.Patch(facecolor="#e6194B",
                                                 label="Aerosol"),
                        matplotlib.patches.Patch(facecolor="#000075",
                                                 label="Cloud"),
                        matplotlib.patches.Patch(facecolor="#42d4f4",
                                                 label="Ice")
                    ]

                    header_legend = ax.legend(handles=header_handles,
                                              loc=(0.3, 1.05),
                                              ncol=3,
                                              frameon=True,
                                              framealpha=1.0,
                                              fontsize=fontsize)

                    ax.add_artist(header_legend)
            ########## END USELEGEND

            if bini in [2, 3]:
                setXlabel = True
            else:
                setXlabel = False

            ax = PlotTweak.setXTicksLabelsAsTime(
                ax,
                ps.time.values,
                xLabelListShow=xLabelListShow,
                xLabelListMajorLine=xLabelListMajorLine,
                setXlabel=setXlabel)

            if bini in [0, 1]:
                ax.set_xticklabels([])

        axes[2].set_yticklabels([str(item) for item in yTicks])
        for tick in axes[2].get_yticklabels():
            print(tick)
            tick.set_visible(True)

        return axes
コード例 #13
0
    def figureUpdraftTimeseries(self):
        packing = 7

        yend = 1.5

        aeroAnalysis = SimulationDataAnalysis(self.simulation, "S_Nabb",
                                              "AeroB")
        cloudAnalysis = SimulationDataAnalysis(self.simulation, "S_Ncbb",
                                               "CloudB")
        iceAnalysis = SimulationDataAnalysis(self.simulation, "S_Nibb", "IceB")

        aeroAnalysis.renameAUXCoordSizeBinB()
        cloudAnalysis.renameAUXCoordSizeBinB()
        iceAnalysis.renameAUXCoordSizeBinB()

        if packing < 7:
            aeroAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)
            cloudAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)
            iceAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)

        aero = aeroAnalysis.simulation.AUXDatasets["AeroB"]["S_Nabb"]
        cloud = cloudAnalysis.simulation.AUXDatasets["CloudB"]["S_Ncbb"]
        ice = iceAnalysis.simulation.AUXDatasets["IceB"]["S_Nibb"]

        updraft = self.simulation.AUXDatasets["Updraft"]["w"]

        updraft = updraft.rename({"ym": "yt"})
        updraft.yt.values = updraft.yt.values - 25.

        dataset = xarray.merge([aero, cloud, ice, updraft])

        aeroColor = Colorful.getDistinctColorList("red")
        cloudColor = Colorful.getDistinctColorList("navy")
        iceColor = Colorful.getDistinctColorList("cyan")

        yticks = numpy.arange(0, 3.5 + 0.1, 0.5)

        heightList = {
            0: "Surface",
            200: "",
            400: "",
            355: "Always below cloud base",
            705: "Always in-cloud",
            785: "At the beginning in-cloud, At end above cloud top",
            850: "Always above cloud top"
        }

        for height in heightList:
            realHeight = dataset.zt.sel(zt=height, method="nearest").item()
            fig = Figure(self.figurefolder,
                         "figureUpdraft_z_" + "{0:.0f}".format(realHeight),
                         ncols=2,
                         nrows=packing,
                         figsize=[8, 16],
                         wspace=0.06,
                         left=0.05,
                         bottom=0.03,
                         top=0.96,
                         right=0.98)

            print("figsize", fig.getFigSize())
            datasetHeight = dataset.sel(zt=height, method="nearest")

            for draftIndex in range(2):
                if draftIndex == 0:
                    dataDraft = datasetHeight.where(
                        datasetHeight["w"] > self.draftLimit, drop=True)
                    draftType = "Up-draft"
                else:
                    dataDraft = datasetHeight.where(
                        datasetHeight["w"] < -self.draftLimit, drop=True)
                    draftType = "Down-draft"

                for bini in range(packing):
                    print("")
                    print("height", realHeight, draftType, "bini", bini)
                    axIndex = bini * 2 + draftIndex
                    ax = fig.getAxes(axIndex)

                    if dataDraft["w"].size == 0:
                        ax.axis("off")
                        continue

                    aeroHeight = dataDraft["S_Nabb"].mean(dim=["xt", "yt"],
                                                          skipna=True)
                    cloudHeight = dataDraft["S_Ncbb"].mean(dim=["xt", "yt"],
                                                           skipna=True)
                    iceHeight = dataDraft["S_Nibb"].mean(dim=["xt", "yt"],
                                                         skipna=True)

                    aeroBin = aeroHeight[:, bini]
                    cloudBin = cloudHeight[:, bini]
                    iceBin = iceHeight[:, bini]

                    totalBin = aeroBin + cloudBin + iceBin

                    aeroFrac = aeroBin / totalBin
                    cloudFrac = cloudBin / totalBin
                    iceFrac = iceBin / totalBin

                    pointZero = totalBin.sel(time=self.xstart,
                                             method="nearest")

                    pointEnd = totalBin.sel(time=self.xend,
                                            method="nearest").values

                    totalBinRelative = totalBin / pointZero

                    aeroFrac.plot(ax=ax, color=aeroColor)
                    cloudFrac.plot(ax=ax, color=cloudColor)
                    iceFrac.plot(ax=ax, color=iceColor)
                    totalBinRelative.plot(ax=ax, color="black")

                    bininame = str(bini + 1)
                    if True:
                        label = " ".join([
                            draftType, "Bin", bininame + ",", "Total",
                            r"$N_0$",
                            str(int(pointZero)) + ",", "\nMin", r"$N$",
                            str(int(pointEnd)), "$(kg^{-1})$"
                        ])
                        facecolor = "black"

                        PlotTweak.setArtist(ax, {label: facecolor},
                                            loc=(0.01, 0.74),
                                            framealpha=0.8)

                        if axIndex == 0:
                            collectionOfLabelsColors = {
                                "Aerosol": aeroColor,
                                "Cloud": cloudColor,
                                "Ice": iceColor
                            }
                            PlotTweak.setArtist(ax,
                                                collectionOfLabelsColors,
                                                ncol=3,
                                                loc=(0.75, 1.12))

                    ##############
                    ax.set_title("")
                    PlotTweak.setXLim(ax, start=self.xstart, end=self.xend)
                    PlotTweak.setYLim(ax, end=yend)

                    PlotTweak.setYticks(ax, yticks)
                    yShownLabelsBoolean = PlotTweak.setYLabels(ax,
                                                               yticks,
                                                               end=3,
                                                               interval=1,
                                                               integer=True)
                    PlotTweak.setYTickSizes(ax, yShownLabelsBoolean)

                    xticks = PlotTweak.setXticks(ax,
                                                 start=self.xstart,
                                                 end=self.xend,
                                                 interval=1)
                    shownLabelsBoolean = PlotTweak.setXLabels(ax,
                                                              xticks,
                                                              end=self.xend,
                                                              interval=4)
                    PlotTweak.setXTickSizes(ax, shownLabelsBoolean)

                    PlotTweak.setYaxisLabel(ax, "")
                    if axIndex in [12, 13]:
                        PlotTweak.setXaxisLabel(ax, "Time", "h")
                    else:
                        PlotTweak.setXaxisLabel(ax, "")
                        PlotTweak.hideXTickLabels(ax)

                    if draftIndex == 1:
                        PlotTweak.hideYTickLabels(ax)
                    if axIndex == 0:
                        ax.text(0.5 * self.xend,
                                yticks[-1] + yticks[1] * 0.25,
                                PlotTweak.getUnitLabel(
                                    "Height\ " + f"{realHeight:.0f}", "m") +
                                " " + heightList[height] + " limit: " +
                                f"{self.draftLimit:.0e}",
                                size=8)

                # end bini for loop
            # end draftIndex for loop
            fig.save()
コード例 #14
0
    def figureUpdraftProfileLog(self):
        packing = 4

        aeroAnalysis = SimulationDataAnalysis(self.simulation, "S_Nabb",
                                              "AeroB")
        cloudAnalysis = SimulationDataAnalysis(self.simulation, "S_Ncbb",
                                               "CloudB")
        iceAnalysis = SimulationDataAnalysis(self.simulation, "S_Nibb", "IceB")

        aeroAnalysis.renameAUXCoordSizeBinB()
        cloudAnalysis.renameAUXCoordSizeBinB()
        iceAnalysis.renameAUXCoordSizeBinB()

        if packing < 7:
            aeroAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)
            cloudAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)
            iceAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)

        aero = aeroAnalysis.simulation.AUXDatasets["AeroB"]["S_Nabb"]
        cloud = cloudAnalysis.simulation.AUXDatasets["CloudB"]["S_Ncbb"]
        ice = iceAnalysis.simulation.AUXDatasets["IceB"]["S_Nibb"]

        updraft = self.simulation.AUXDatasets["Updraft"]["w"]

        updraft = updraft.rename({"ym": "yt"})
        updraft.yt.values = updraft.yt.values - 25.

        dataset = xarray.merge([aero, cloud, ice, updraft])

        aeroColor = Colorful.getDistinctColorList("red")
        cloudColor = Colorful.getDistinctColorList("navy")
        iceColor = Colorful.getDistinctColorList("cyan")

        ystart = 400.
        yend = 850.

        fig = Figure(self.figurefolder,
                     "figureProfileDraftsLog",
                     figsize=[4.724409448818897, 2.5],
                     ncols=2,
                     nrows=1,
                     wspace=0.06,
                     left=0.12,
                     bottom=0.12,
                     top=0.86,
                     right=0.98)
        print("figsize", fig.getFigSize())

        timeBegin = dataset.time.sel(time=self.xstart, method="nearest").item()
        timeEnd = dataset.time.sel(time=self.xend, method="nearest").item()
        datasetTime = dataset.sel(time=slice(timeBegin, timeEnd))

        subFigureName = [chr(ord('a') + i) for i in range(packing * 2)]
        loopedBins = range(packing)[1:2]
        for draftIndex in range(2):
            if draftIndex == 0:
                dataDraft = datasetTime.where(
                    datasetTime["w"] > self.draftLimit, drop=True)
                draftType = "Up-draft"
            else:
                dataDraft = datasetTime.where(
                    datasetTime["w"] < -self.draftLimit, drop=True)
                draftType = "Down-draft"

            biniCounter = 0
            for bini in loopedBins:
                print("")
                print(draftType, "timeBegin", timeBegin, "timeEnd", timeEnd)
                axIndex = biniCounter * 2 + draftIndex
                biniCounter += 1
                ax = fig.getAxes(axIndex)

                if dataDraft["w"].size == 0:
                    ax.axis("off")
                    continue

                aeroHeight = dataDraft["S_Nabb"].mean(dim=["xt", "yt", "time"],
                                                      skipna=True)
                cloudHeight = dataDraft["S_Ncbb"].mean(
                    dim=["xt", "yt", "time"], skipna=True)
                iceHeight = dataDraft["S_Nibb"].mean(dim=["xt", "yt", "time"],
                                                     skipna=True)

                aeroBin = aeroHeight[bini, :]
                cloudBin = cloudHeight[bini, :]
                iceBin = iceHeight[bini, :]

                aeroFrac = numpy.log10(aeroBin)
                cloudFrac = numpy.log10(cloudBin)
                iceFrac = numpy.log10(iceBin)

                aeroFrac.plot(ax=ax, color=aeroColor, y="zt")
                cloudFrac.plot(ax=ax, color=cloudColor, y="zt")
                iceFrac.plot(ax=ax, color=iceColor, y="zt")

                if packing < 7:
                    if bini == (packing - 1):
                        bininame = str(bini + 1) + " - 7"
                    else:
                        bininame = str(bini + 1)
                else:
                    bininame = str(bini + 1)

                ##############
                ax.set_title("")

                PlotTweak.setYLim(ax, start=ystart, end=yend)
                yticks = PlotTweak.setYticks(ax,
                                             start=ystart,
                                             end=yend,
                                             interval=50)
                shownYLabelsBoolean = PlotTweak.setYLabels(ax,
                                                           yticks,
                                                           end=yend,
                                                           interval=100,
                                                           integer=False)
                PlotTweak.setYTickSizes(ax, shownYLabelsBoolean)

                xlimits = ax.get_xlim()
                ylimits = ax.get_ylim()
                print("limits", xlimits, ylimits)

                PlotTweak.setXaxisLabel(ax, "")
                PlotTweak.setYaxisLabel(ax, "")

                if draftIndex == 0:
                    PlotTweak.setYaxisLabel(ax, "Height", "m")

                if draftIndex == 1:
                    PlotTweak.hideYTickLabels(ax)

                if axIndex == 0:
                    ax.text( 0.1*(xlimits[1]-xlimits[0])+xlimits[0], (ylimits[1]-ylimits[0])*0.05+ylimits[1],
                            "Mean profile from " + PlotTweak.getUnitLabel(f"t_0={self.xstart}", "h")+\
                                " to " +  PlotTweak.getUnitLabel(f"t_1={self.xend}", "h") +\
                                    " limit: " + f"{self.draftLimit:.0e}"  , size=8)
                if True:
                    label = " ".join([
                        subFigureName[axIndex] + ")", draftType, "Bin",
                        bininame
                    ])

                    PlotTweak.setAnnotation(
                        ax,
                        label,
                        xPosition=0.08 * (xlimits[1] - xlimits[0]) +
                        xlimits[0],
                        yPosition=0.08 * (ylimits[1] - ylimits[0]) +
                        ylimits[0])

                    if axIndex == 0:
                        collectionOfLabelsColors = {
                            "Aerosol": aeroColor,
                            "Cloud": cloudColor,
                            "Ice": iceColor
                        }
                        PlotTweak.setArtist(ax,
                                            collectionOfLabelsColors,
                                            ncol=3,
                                            loc=(0.15, 1.19))

            # end bini for loop
        # end draftIndex for loop
        fig.save()
コード例 #15
0
    def figureUpdraftProfile(self):
        packing = 7

        aeroAnalysis = SimulationDataAnalysis(self.simulation, "S_Nabb",
                                              "AeroB")
        cloudAnalysis = SimulationDataAnalysis(self.simulation, "S_Ncbb",
                                               "CloudB")
        iceAnalysis = SimulationDataAnalysis(self.simulation, "S_Nibb", "IceB")

        aeroAnalysis.renameAUXCoordSizeBinB()
        cloudAnalysis.renameAUXCoordSizeBinB()
        iceAnalysis.renameAUXCoordSizeBinB()

        if packing < 7:
            aeroAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)
            cloudAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)
            iceAnalysis.packFilteredAUXVariablewithSizeBinCoords(packing)

        aero = aeroAnalysis.simulation.AUXDatasets["AeroB"]["S_Nabb"]
        cloud = cloudAnalysis.simulation.AUXDatasets["CloudB"]["S_Ncbb"]
        ice = iceAnalysis.simulation.AUXDatasets["IceB"]["S_Nibb"]

        updraft = self.simulation.AUXDatasets["Updraft"]["w"]

        updraft = updraft.rename({"ym": "yt"})
        if xarray.__version__ == "0.14.1":
            updraft.yt.values = updraft.yt.values - 25.
        else:
            updraft = updraft.assign_coords(yt=(updraft.yt.values - 25.))

        dataset = xarray.merge([aero, cloud, ice, updraft])

        aeroColor = Colorful.getDistinctColorList("red")
        cloudColor = Colorful.getDistinctColorList("navy")
        iceColor = Colorful.getDistinctColorList("cyan")
        totalColor = Colorful.getDistinctColorList("green")

        xaxisend = 1.0
        ystart = 400.
        yend = 850.

        loopedBins = range(packing)[1:3]

        fig = Figure(self.figurefolder,
                     "figure8",
                     figsize=[4.724409448818897, 3],
                     ncols=2,
                     nrows=len(loopedBins),
                     wspace=0.06,
                     left=0.12,
                     bottom=0.12,
                     top=0.85,
                     right=0.98)
        print("figsize", fig.getFigSize())

        timeBegin = dataset.time.sel(time=self.xstart, method="nearest").item()
        timeEnd = dataset.time.sel(time=self.xend, method="nearest").item()
        datasetTime = dataset.sel(time=slice(timeBegin, timeEnd))

        subFigureName = [chr(ord('a') + i) for i in range(packing * 2)]

        for draftIndex in range(2):
            if draftIndex == 0:
                dataDraft = datasetTime.where(
                    datasetTime["w"] > self.draftLimit, drop=True)
                draftType = "Up-draft"
            else:
                dataDraft = datasetTime.where(
                    datasetTime["w"] < -self.draftLimit, drop=True)
                draftType = "Down-draft"

            biniCounter = 0
            for bini in loopedBins:
                print("")
                print(draftType, "timeBegin", timeBegin, "timeEnd", timeEnd)
                axIndex = biniCounter * 2 + draftIndex

                ax = fig.getAxes(axIndex)

                if dataDraft["w"].size == 0:
                    ax.axis("off")
                    continue

                aeroHeight = dataDraft["S_Nabb"].mean(dim=["xt", "yt", "time"],
                                                      skipna=True)
                cloudHeight = dataDraft["S_Ncbb"].mean(
                    dim=["xt", "yt", "time"], skipna=True)
                iceHeight = dataDraft["S_Nibb"].mean(dim=["xt", "yt", "time"],
                                                     skipna=True)

                aeroBin = aeroHeight[bini, :]
                cloudBin = cloudHeight[bini, :]
                iceBin = iceHeight[bini, :]

                totalBin = aeroBin + cloudBin + iceBin

                aeroFrac = aeroBin / totalBin
                cloudFrac = cloudBin / totalBin
                iceFrac = iceBin / totalBin

                pointMax = totalBin.max()

                totalBinRelative = totalBin / pointMax.item()
                totalBinRelative.plot(ax=ax, color=totalColor, y="zt")

                cloudFrac.plot(ax=ax, color=cloudColor, y="zt")
                aeroFrac.plot(ax=ax, color=aeroColor, y="zt")
                iceFrac.plot(ax=ax, color=iceColor, y="zt")

                if packing < 7:
                    if bini == (packing - 1):
                        bininame = str(bini + 1) + " - 7"
                    else:
                        bininame = str(bini + 1)
                else:
                    bininame = str(bini + 1)

                ##############
                ax.set_title("")

                PlotTweak.setYLim(ax, start=ystart, end=yend)
                yticks = PlotTweak.setYticks(ax,
                                             start=ystart,
                                             end=yend,
                                             interval=50)
                shownYLabelsBoolean = PlotTweak.setYLabels(ax,
                                                           yticks,
                                                           end=yend,
                                                           interval=100,
                                                           integer=False)
                PlotTweak.setYTickSizes(ax, shownYLabelsBoolean)

                PlotTweak.setXLim(ax, end=xaxisend)
                xticks = PlotTweak.setXticks(ax,
                                             end=xaxisend,
                                             interval=0.1,
                                             integer=False)
                xTickLabels = copy.deepcopy(xticks)
                for xtickInd, xtickValue in enumerate(xTickLabels):
                    if (xtickInd == 0) or (xtickValue == xTickLabels[-1]):
                        xTickLabels[xtickInd] = f"{xtickValue:.0f}"
                    else:
                        xTickLabels[xtickInd] = f"{xtickValue:.1f}"

                xShownLabelsBoolean = PlotTweak.setXLabels(ax,
                                                           xticks,
                                                           end=xaxisend,
                                                           interval=0.2,
                                                           integer=False)
                ax.set_xticklabels(xTickLabels)
                PlotTweak.setXTickSizes(ax, xShownLabelsBoolean)

                xlimits = ax.get_xlim()
                ylimits = ax.get_ylim()
                PlotTweak.setXaxisLabel(ax, "")
                PlotTweak.setYaxisLabel(ax, "")

                print("bini", biniCounter, "loopedBins -1",
                      len(loopedBins) - 1)
                if (biniCounter != len(loopedBins) - 1):
                    PlotTweak.hideXTickLabels(ax)

                if draftIndex == 0:
                    PlotTweak.setYaxisLabel(ax, "Height", "m")

                if draftIndex == 1:
                    PlotTweak.hideYTickLabels(ax)

                if axIndex == 0:
                    ax.text( 0.05*(xlimits[1]-xlimits[0]), (ylimits[1]-ylimits[0])*0.05+ylimits[1],
                            "Mean profile from " + PlotTweak.getUnitLabel(f"t_0={self.xstart}", "h")+\
                                " to " +  PlotTweak.getUnitLabel(f"t_1={self.xend}", "h") +\
                                    " limit: " + PlotTweak.getUnitLabel(f"{self.draftLimit:.1f}", "m\ s^{-1}")
                            , size=8)
                if True:
                    label = " ".join([
                        subFigureName[axIndex] + ")", draftType, "Bin",
                        bininame
                    ])

                    PlotTweak.setAnnotation(
                        ax,
                        label,
                        xPosition=0.05 * (xlimits[1] - xlimits[0]) +
                        xlimits[0],
                        yPosition=0.1 * (ylimits[1] - ylimits[0]) + ylimits[0])

                    if axIndex == 0:
                        collectionOfLabelsColors = {
                            "Aerosol": aeroColor,
                            "Cloud": cloudColor,
                            "Ice": iceColor,
                            "Total": totalColor
                        }
                        PlotTweak.setArtist(ax,
                                            collectionOfLabelsColors,
                                            ncol=4,
                                            loc=(0.10, 1.19))
                biniCounter += 1

            # end bini for loop
        # end draftIndex for loop
        fig.save()
コード例 #16
0
def main(simulationDataFrameCSVFile):

    simulationDataFrame = pandas.read_csv(simulationDataFrameCSVFile)

    # set simulation data as dictionary
    simulationCollection = InputSimulation.getSimulationCollection(
        simulationDataFrame)

    if False:
        fig1 = Figure("/home/aholaj/Nextcloud/kuvatesti", "Prognostic")

        cloudTicks = Plot.getTicks(0, 1000, 250)

        logaritmicLevels = Plot.getLogaritmicTicks(-17, -9, includeFives=True)

        ax, im = Plot.getTimeseriesOfProfile(
            fig1.getAxes(),
            simulationCollection["Prognostic_48h"],
            "P_cDUa",
            title="",
            yticks=cloudTicks,
            timeEndH=33.05,
            levels=logaritmicLevels,
            useColorBar=False,
            showXaxisLabels=False,
            showXLabel=False)

        fig1.save()
    if False:
        # create figure object
        fig2 = Figure("/home/aholaj/Nextcloud/kuvatesti", "LWP")
        # load ts-datasets and change their time coordinates to hours
        for k in [
                "Prognostic_48h", "ICE4_24h", "Prognostic_2",
                "Prognostic_Aero", "Prognostic_2_Aero"
        ]:
            simulationCollection[k].getTSDataset()
            simulationCollection[k].setTimeCoordToHours()

        # plot timeseries with unit conversion
        Plot.getTimeseries(fig2.getAxes(), [
            simulationCollection["Prognostic_48h"],
            simulationCollection["ICE4_24h"],
            simulationCollection["Prognostic_Aero"],
            simulationCollection["Prognostic_2"],
            simulationCollection["Prognostic_2_Aero"]
        ],
                           "lwp_bar",
                           conversionFactor=1000.)
        end = 32
        # set xticks
        ticks = PlotTweak.setXticks(fig2.getAxes(), end=end, interval=0.5)
        # set xlabels
        shownLabelsBoolean = PlotTweak.setXLabels(fig2.getAxes(),
                                                  ticks,
                                                  end=end,
                                                  interval=4)
        # set xtick sizes
        PlotTweak.setXTickSizes(fig2.getAxes(),
                                shownLabelsBoolean,
                                minorFontSize=8)
        # limit x-axes
        PlotTweak.setXLim(fig2.getAxes(), end=end)
        PlotTweak.setYLim(fig2.getAxes(), end=60)
        # set annotation for figure
        PlotTweak.setAnnotation(fig2.getAxes(),
                                "a) Liquid water path",
                                xPosition=2,
                                yPosition=30)

        Plot.getVerticalLine(fig2.getAxes(), 2)
        # set axes labels
        PlotTweak.setXaxisLabel(fig2.getAxes(), "LWP", "g\ m^{-2}")
        PlotTweak.setYaxisLabel(fig2.getAxes(), "Time", "h")
        PlotTweak.useLegend(fig2.getAxes())
        PlotTweak.setTightLayot(fig2.getFig())

        fig2.save()

    if True:
        # create figure object
        fig2 = Figure("/home/aholaj/Nextcloud/kuvatesti", "Nc_ic")
        # load ts-datasets and change their time coordinates to hours
        sensitive = [
            "ICE0_8h", "ICE1_24h", "ICE2_24h", "ICE3_24h", "ICE3_8h",
            "ICE4_24h", "ICE5_8h", "ICE6_8h", "Prognostic_48h"
        ]
        for k in sensitive:
            simulationCollection[k].getTSDataset()
            simulationCollection[k].setTimeCoordToHours()

            # plot timeseries with unit conversion
            Plot.getTimeseries(fig2.getAxes(),
                               simulationCollection[k],
                               "Nc_ic",
                               conversionFactor=1e-6)
        end = 32
        # set xticks
        ticks = PlotTweak.setXticks(fig2.getAxes(), end=end, interval=0.5)
        # set xlabels
        shownLabelsBoolean = PlotTweak.setXLabels(fig2.getAxes(),
                                                  ticks,
                                                  end=end,
                                                  interval=4)
        # set xtick sizes
        PlotTweak.setXTickSizes(fig2.getAxes(),
                                shownLabelsBoolean,
                                minorFontSize=8)
        # limit x-axes
        PlotTweak.setXLim(fig2.getAxes(), end=end)
        #PlotTweak.setYLim(fig2.getAxes(), end = 60)
        # set annotation for figure
        PlotTweak.setAnnotation(fig2.getAxes(),
                                "a) Nc_ic",
                                xPosition=2,
                                yPosition=155)

        Plot.getVerticalLine(fig2.getAxes(), 2)
        # set axes labels
        PlotTweak.setYaxisLabel(fig2.getAxes(), "In-cloud\ CDNC", "mg^{-1}")
        PlotTweak.setXaxisLabel(fig2.getAxes(), "Time", "h")
        PlotTweak.useLegend(fig2.getAxes())
        PlotTweak.setTightLayot(fig2.getFig())

        fig2.save(file_extension=".png")
    if True:
        # create figure object
        fig3 = Figure("/home/aholaj/Nextcloud/kuvatesti", "IWP")
        # load ts-datasets and change their time coordinates to hours
        for k in [
                "Prognostic_48h", "ICE4_24h", "Prognostic_2",
                "Prognostic_Aero", "Prognostic_2_Aero"
        ]:
            simulationCollection[k].getTSDataset()
            #simulationCollection[k].setTimeCoordToHours()

        # plot timeseries with unit conversion
        Plot.getTimeseries(fig3.getAxes(), [
            simulationCollection["Prognostic_48h"],
            simulationCollection["ICE4_24h"],
            simulationCollection["Prognostic_Aero"],
            simulationCollection["Prognostic_2"],
            simulationCollection["Prognostic_2_Aero"]
        ],
                           "iwp_bar",
                           conversionFactor=1000.)
        end = 32
        # set xticks
        ticks = PlotTweak.setXticks(fig3.getAxes(), end=end, interval=0.5)
        # set xlabels
        shownLabelsBoolean = PlotTweak.setXLabels(fig3.getAxes(),
                                                  ticks,
                                                  end=end,
                                                  interval=4)
        # set xtick sizes
        PlotTweak.setXTickSizes(fig3.getAxes(),
                                shownLabelsBoolean,
                                minorFontSize=8)
        # limit x-axes
        PlotTweak.setXLim(fig3.getAxes(), end=end)
        PlotTweak.setYLim(fig3.getAxes(), end=60)
        # set annotation for figure
        PlotTweak.setAnnotation(fig3.getAxes(),
                                "b) Ice water path",
                                xPosition=2,
                                yPosition=30)

        Plot.getVerticalLine(fig3.getAxes(), 2)
        # set axes labels
        PlotTweak.setXaxisLabel(fig3.getAxes(), "IWP", "g\ m^{-2}")
        PlotTweak.setYaxisLabel(fig3.getAxes(), "Time", "h")
        PlotTweak.useLegend(fig3.getAxes())
        PlotTweak.setTightLayot(fig3.getFig())

        fig3.save()

    if False:
        # create figure object
        fig2 = Figure("/home/aholaj/Nextcloud/kuvatesti",
                      "fourWinds",
                      ncols=2,
                      nrows=2,
                      style="seaborn-paper")
        # load ts-datasets and change their time coordinates to hours
        for k in ["ICE0_8h", "ICE1_8h"]:
            simulationCollection[k].getTSDataset()
            simulationCollection[k].getPSDataset()
            simulationCollection[k].setTimeCoordToHours()

        # plot timeseries with unit conversion
        Plot.getTimeseries(fig2.getAxes()[0, 0],
                           simulationCollection["ICE0_8h"],
                           "lwp_bar",
                           conversionFactor=1000.)
        Plot.getVerticalLine(fig2.getAxes()[0, 0], 2)

        if True:
            PlotTweak.setSuperWrapper(
                fig2.getAxes()[0, 0],
                xstart=0,
                xend=8,
                xtickinterval=0.5,
                xlabelinterval=2,
                xticks=None,
                xShownLabels=None,
                xTickMajorFontSize=
                3.5,  # matplotlib.rcParams["xtick.major.size"],
                yTickMajorFontSize=
                3.5,  #matplotlib.rcParams["ytick.major.size"],
                ystart=0,
                yend=60,
                ytickinterval=2,
                ylabelinterval=10,
                yticks=None,
                yShownLabels=None,
                annotationText=None,
                annotationXPosition=2,
                annotationYPosition=30,
                xlabel="Time",
                xunit="h",
                ylabel="LWP",
                yunit="g\ m^{-2}",
                useBold=True)
        PlotTweak.hideYTickLabels(fig2.getAxes()[0, 0])

        PlotTweak.setAxesOff(fig2.getAxes()[0, 1])
        PlotTweak.setLegendSimulation(
            fig2.getAxes()[0, 1],
            [simulationCollection["ICE0_8h"], simulationCollection["ICE1_8h"]])

        ax, im, levels = Plot.getTimeseriesOfProfile(
            fig2.getAxes()[1, 1],
            simulationCollection["ICE0_8h"],
            "P_RH",
            levels=None,
            useLogaritmic=False,
            colors=None)
        PlotTweak.setAxesOff(fig2.getAxes()[1, 0])
        cax = matplotlib.pyplot.axes([0.05, 0.25, 0.3, 0.03])
        Plot.getColorBar(im, cax, levels)

        #Plot.getContourLine(fig2.getAxes()[1,1],"ICE0_8h", color =  'black' , value = 100)

        fig2.save()
コード例 #17
0
    def figureProfileExample(self):

        fig = Figure(self.figurefolder,
                     "figureProfileExample",
                     figsize=[4.724409448818897, 4],
                     ncols=2,
                     nrows=1,
                     wspace=0.15,
                     bottom=0.13,
                     left=0.14)
        print(fig.getFigSize())
        colorList = [
            Colorful.getDistinctColorList("red"),
            Colorful.getDistinctColorList("blue")
        ]
        variables = ["temperature", "water"]

        tempRef = None
        for ind, temp in enumerate(self.soundIN["temperature"].values):
            if tempRef is None:
                tempRef = temp
            else:
                if numpy.abs(tempRef - temp) > numpy.finfo(float).eps * 10:
                    pblhIND = ind - 1
                    break
        pblh = self.soundIN["height"].iloc[pblhIND]

        tpot_inv = self.design["tpot_inv"].iloc[self.designInd]
        tpot_pbl = self.design["tpot_pbl"].iloc[self.designInd]

        r_t = self.soundIN["water"].max()
        q_inv = self.design["q_inv"].iloc[self.designInd]

        t_grad = 0.3
        invThi = tpot_inv / t_grad

        print("pblh", pblh)

        maxheight = Data.roundUp(self.soundIN["height"].max(), 100)

        minTemp = Data.roundDown(self.soundIN["temperature"].min(), 1)
        maxTemp = Data.roundUp(self.soundIN["temperature"].max(), 1)

        minWater = 0
        maxWaterAxes = Data.roundUp(self.soundIN["water"].max(), 1)

        print("maxWater", self.soundIN["water"].max())

        for ind in range(2):
            ax = fig.getAxes(ind)

            self.soundIN.plot(ax=ax,
                              x=variables[ind],
                              y="height",
                              color=colorList[ind],
                              legend=False,
                              linewidth=2)

            ax.set_ylim([0, maxheight])

            Plot.getHorizontalLine(ax, pblh)
            if ind == 0:
                PlotTweak.setXaxisLabel(ax, "\\theta_{L}", "K")
                PlotTweak.setYaxisLabel(ax, "Altitude", "m")

                xticks = PlotTweak.setXticks(ax,
                                             start=minTemp,
                                             end=maxTemp,
                                             interval=1,
                                             integer=True)

                xShownLabelsBoolean = PlotTweak.setXLabels(ax,
                                                           xticks,
                                                           start=minTemp,
                                                           end=maxTemp,
                                                           interval=5,
                                                           integer=True)

                PlotTweak.setXTickSizes(ax, xShownLabelsBoolean)
                ax.set_xlim([minTemp, maxTemp])

                xmin = ax.get_xlim()[0]
                xmax = ax.get_xlim()[1]

                ymin = ax.get_ylim()[0]
                ymax = ax.get_ylim()[1]

                k_rate = (ymax - ymin) / (xmax - xmin)

                xPoint = (xmax - xmin) * 0.2 + xmin
                yPoint = k_rate * (xPoint - tpot_pbl)

                PlotTweak.setAnnotation(ax,
                                        "(a) Temperature profile",
                                        xPosition=(xmax - xmin) * 0.05 + xmin,
                                        yPosition=(ymax - ymin) * 0.95 + ymin)

                ax.axvline(tpot_pbl + tpot_inv,
                           color="k",
                           linestyle="--",
                           ymax=(pblh + invThi) / ymax)

                # ax.arrow(xPoint, yPoint, tpot_pbl-xPoint, 0-yPoint,
                #           facecolor='black', shape = "full", linewidth = param, head_length = param*1.5*3., head_width = 3.*param, overhang = 0.1, head_starts_at_zero = True, length_includes_head = True)
                ax.annotate(PlotTweak.getMathLabel("tpot_pbl"),
                            xy=(tpot_pbl, 0),
                            xytext=(xPoint, yPoint),
                            arrowprops=dict(facecolor='black',
                                            arrowstyle="->",
                                            linewidth=1.5),
                            horizontalalignment='left',
                            verticalalignment='bottom')
                #ax.text((xPoint-tpot_pbl)*0.6 + tpot_pbl, (yPoint- ymin)*0.3 + ymin,  PlotTweak.getMathLabel("tpot_pbl"))
                arrowParam = 0.3
                pblhArrowX = (xmax -
                              (tpot_pbl + tpot_inv)) * arrowParam + (tpot_pbl +
                                                                     tpot_inv)
                pblhArrowXText = (xmax -
                                  (tpot_pbl + tpot_inv)) * arrowParam * 1.5 + (
                                      tpot_pbl + tpot_inv)
                ax.annotate("",
                            xy=(pblhArrowX, pblh),
                            xytext=(pblhArrowX, 0),
                            arrowprops=dict(arrowstyle="<->",
                                            facecolor='black',
                                            linewidth=1.5))
                ax.text(pblhArrowXText, pblh * 0.43, "PBLH", rotation=90)

                ax.text(tpot_pbl + tpot_inv * 0.40, pblh * 0.43,
                        PlotTweak.getMathLabel("tpot_inv"))
                ax.annotate("",
                            xy=(tpot_pbl, pblh * 0.5),
                            xytext=(tpot_pbl + tpot_inv, pblh * 0.5),
                            arrowprops=dict(arrowstyle="<->",
                                            facecolor='black',
                                            linewidth=1.5))

            else:

                PlotTweak.setXaxisLabel(ax, "r_t", "g\ kg^{-1}")
                PlotTweak.hideYTickLabels(ax)

                xticks = numpy.arange(minWater, maxWaterAxes + 0.001, 1)
                xlabels = [f"{t:.1f}" for t in xticks]

                xShowList = Data.getMaskedList(xticks, xticks[0::4])

                ax.set_xticks(xticks)
                ax.set_xticklabels(xlabels)
                PlotTweak.setXTickSizes(ax, xShowList)
                PlotTweak.hideLabels(ax.xaxis, xShowList)
                ax.set_xlim([minWater, maxWaterAxes])

                xmin = ax.get_xlim()[0]
                xmax = ax.get_xlim()[1]

                ymin = ax.get_ylim()[0]
                ymax = ax.get_ylim()[1]

                PlotTweak.setAnnotation(ax,
                                        "(b) Humidity profile",
                                        xPosition=(xmax - xmin) * 0.17 + xmin,
                                        yPosition=(ymax - ymin) * 0.95 + ymin)

                ax.axvline(r_t - q_inv,
                           color="k",
                           linestyle="--",
                           ymax=(pblh + invThi) / ymax)

                k_rate = (ymax - ymin) / (xmin - xmax)

                xPoint = self.soundIN["water"].max() * .8
                yPoint = k_rate * (xPoint - self.soundIN["water"].max())

                ax.annotate(PlotTweak.getLatexLabel("r_t"),
                            xy=(self.soundIN["water"].max() * 0.99, 0),
                            xytext=(xPoint, yPoint),
                            arrowprops=dict(facecolor='black',
                                            arrowstyle="->",
                                            linewidth=1.5),
                            horizontalalignment='left',
                            verticalalignment='bottom')
                ax.annotate("",
                            xy=(r_t - q_inv, pblh * 0.5),
                            xytext=(r_t, pblh * 0.5),
                            arrowprops=dict(arrowstyle="<->",
                                            facecolor='black',
                                            linewidth=1.5))
                ax.text(r_t - q_inv * 0.60, pblh * 0.43,
                        PlotTweak.getMathLabel("q_inv"))

            yticks = PlotTweak.setYticks(ax,
                                         start=0,
                                         end=maxheight,
                                         interval=100,
                                         integer=True)

            yShownLabelsBoolean = PlotTweak.setYLabels(ax,
                                                       yticks,
                                                       start=0,
                                                       end=maxheight,
                                                       interval=500)

            PlotTweak.setYTickSizes(ax, yShownLabelsBoolean)

            # yTicks = numpy.arange(0, 0.51, 0.1)
            # yTickLabels = [f"{t:.1f}" for t in yTicks]
            #
            # ax.set_yticklabels(yTickLabels)
            # ax.set_ylim([0, 0.5])
            # PlotTweak.setAnnotation(ax, self.annotationCollection[trainingSet], xPosition=ax.get_xlim()[1]*0.20, yPosition = ax.get_ylim()[1]*0.90)
            # PlotTweak.setXaxisLabel(ax,"")

        # fig.getAxes(0).legend(handles=PlotTweak.getPatches(legendLabelColors),
        #                         title = "Global variance -based sensitivity for " + PlotTweak.getLatexLabel("w_{pos}", False),
        #               loc=(-0.2,-2.6),
        #               ncol = 4,
        #               fontsize = 8)

        fig.save()
コード例 #18
0
    def figure7(self):

        fig = Figure(self.figurefolder,"figure7", ncols = 2, nrows = 2, hspace=0.43, bottom = 0.14, left=0.15, top=0.98, wspace = 0.1)

        simulation = "Prognostic_48h"

        self.simulationCollection[simulation].getPSDataset()
        self.simulationCollection[simulation].setTimeCoordToHours()

        end = 1000
        yPositionFrac = 0.9
        xPositionFrac = 0.02

        annotation = ["a) Liquid water mixing ratio", "b) Ice mixing ratio", "c) Freezing rate"]
        muuttujalista = ["P_rl", "P_ri", "nucl_ni"]
        aika = [2,4,16,32]
        colorlist = ['#a6cee3','#1f78b4','#b2df8a','#33a02c'] #['#a63603', '#e6550d', '#fd8d3c', '#fdae6b'] #['#1b9e77','#d95f02','#7570b3','#e7298a']

        startList = [0, 0, -5]
        endList = [0.2, 0.025,2.5]

        xPositionList = []

        for ind, muuttuja in enumerate(muuttujalista):
            ax = fig.getAxes(ind)
            data = self.simulationCollection[simulation].getPSDataset()[muuttuja]

            xPositionList.append( numpy.abs(startList[ind]-endList[ind])*xPositionFrac + startList[ind])

            if muuttuja == "nucl_ni":
                data.values  = numpy.log10(data.values)
            else:
                data.values = data.values*1e3


            for aikaInd, aikapiste in enumerate(aika):

                data.sel(time = aikapiste, method="nearest").plot( y="zt", ax = ax, color = colorlist[aikaInd])

        end = 1000
        for ind in range(3):
            ax = fig.getAxes(ind)
            ax.set_title("")
            PlotTweak.setYLim(ax, end = end)
            ticks = PlotTweak.setYticks(ax, end = end, interval = 100)
            shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 200)
            PlotTweak.setYTickSizes(ax, shownLabelsBoolean)
            PlotTweak.setAnnotation(ax, annotation[ind], xPosition= xPositionList[ind], yPosition= yPositionFrac*end)


        ###
        ind = 0
        ax = fig.getAxes(ind)
        start = startList[ind]
        end = endList[ind]
        PlotTweak.setXLim(ax, start = ind, end = end)
        PlotTweak.setXaxisLabel(ax,"", "g\ kg^{-1}")
        PlotTweak.setYaxisLabel(ax,"Height", "m")

        matplotlib.pyplot.setp(ax.get_xticklabels()[-1], visible=False)

        ###
        ind = 1
        ax = fig.getAxes(ind)
        start = startList[ind]
        end = endList[ind]
        PlotTweak.setXLim(ax, start = start, end = end)
        PlotTweak.setXaxisLabel(ax,"", "g\ kg^{-1}")
        PlotTweak.setYaxisLabel(ax,"")
        PlotTweak.hideYTickLabels(ax)


        ticks = PlotTweak.setXticks(ax, end = end, interval = 0.005/2, integer=False)
        shownLabelsBoolean = PlotTweak.setXLabels(ax, ticks, end = end, interval = 0.005, integer = False)
        PlotTweak.setXTickSizes(ax, shownLabelsBoolean)
        matplotlib.pyplot.setp(ax.get_xticklabels()[-1], visible=False)

        ###
        ind = 2
        ax = fig.getAxes(ind)
        start = startList[ind]
        end = endList[ind]
        PlotTweak.setYaxisLabel(ax,"Height", "m")
        PlotTweak.setXaxisLabel(ax,"", "m^{-3}\ s^{-1}")
        PlotTweak.setXLim(ax, start = start, end = end)

        xticksLog = numpy.arange(start, end + 0.1, 2.5)
        xlabelsLog = [r"$10^{" + "{0:.1f}".format(elem) + "}$" for elem in xticksLog]
        ax.set_xticks(xticksLog)
        ax.set_xticklabels(xlabelsLog)

        # empty space
        ax = fig.getAxes(3)
        ax.axis("off")
        legend_elements = [Patch(facecolor=colorlist[0], label='2 (h)'),
                       Patch(facecolor=colorlist[1], label='4 (h)'),
                       Patch(facecolor=colorlist[2], label='16 (h)'),
                       Patch(facecolor=colorlist[3], label='32 (h)')]

        ax.legend(handles=legend_elements, loc="center", frameon = True, framealpha = 1.0)
        fig.save()
コード例 #19
0
    def finaliseLatexTables(self):
        for texFile in self.tableFolder.glob("**/*.tex"):
            linesToBeWritten = []
            with open(texFile, "r") as readFile:
                for line in readFile:

                    line = line.replace(" ", "")

                    line = line.replace("toprule", "tophline")

                    line = line.replace("midrule", "middlehline")
                    line = line.replace("bottomrule", "bottomhline")

                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{cos\\_\\{\\textbackslashmu\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("cos_mu"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{N\\_\\{" +
                        PlotTweak.getMathLabelSubscript("as") +
                        "\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("as"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{N\\_\\{" +
                        PlotTweak.getMathLabelSubscript("ks") +
                        "\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("ks"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{N\\_\\{" +
                        PlotTweak.getMathLabelSubscript("cs") +
                        "\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("cs"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{w\\_\\{lin.fit\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("w2pos_linearFit"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{\\{\\textbackslashtheta\\}\\_\\{L\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("tpot_pbl"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{\\textbackslashDelta\\{\\textbackslashtheta\\}\\_\\{L\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("tpot_inv"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{\\textbackslashDeltaq\\_\\{L\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("q_inv"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{r\\_\\{eff\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("rdry_AS_eff"))
                    line = line.replace(
                        "\\$\\textbackslashmathbf\\{\\{H\\_\\{PBL\\}\\}\\{\\textbackslash\\}\\}\\$",
                        PlotTweak.getMathLabelTableFormat("pblh"))

                    line = line.replace("mathLabel", "Variable")
                    line = line.replace(
                        "relativeCombined",
                        "Product of relative permutation feature importances")
                    line = line.replace(
                        "zeros",
                        "Number of times relative importance equal to zero")
                    line = line.replace(
                        "relativeImportance",
                        "Relative permutation feature importance")

                    line = line.replace("rSquared", "$R^2$")
                    line = line.replace("r\\_value", "R")

                    line = line.replace("emulator",
                                        self.predictorClearNames["emulator"])
                    line = line.replace("linearFit",
                                        self.predictorClearNames["linearFit"])
                    line = line.replace(
                        "correctedLinearFit",
                        self.predictorClearNames["correctedLinearFit"])

                    line = line.replace("\\_Mean", " mean")
                    line = line.replace("\\_Std", " std")
                    line = line.replace("\\#", " ")

                    linesToBeWritten.append(line)
            texFile.unlink()
            with open(texFile, "w") as writeFile:
                for line in linesToBeWritten:
                    writeFile.write(line)
コード例 #20
0
figObject.simulationCollection["RadDamp"].setColor(
    Colorful.getDistinctColorList("red"))
lwpYlimit = 60
iwpYlimit = 21
yPositionFrac = 0.91

# figA
ax = fig.getAxes(0)
for k in simulationList.getIce0Simulations():
    Plot.getTimeseries(ax,
                       figObject.simulationCollection[k],
                       "lwp_bar",
                       conversionFactor=1000.)
PlotTweak.setAnnotation(ax,
                        "a) ICE0 liquid water path",
                        xPosition=0.2,
                        yPosition=lwpYlimit * yPositionFrac)

# figB
ax = fig.getAxes(2)
for k in simulationList.getIce1Simulations():
    Plot.getTimeseries(ax,
                       figObject.simulationCollection[k],
                       "lwp_bar",
                       conversionFactor=1000.)
PlotTweak.setAnnotation(ax,
                        "b) ICE1 liquid water path",
                        xPosition=0.2,
                        yPosition=lwpYlimit * yPositionFrac)

# figC
コード例 #21
0
    def figure4(self):

        fig = Figure(self.figurefolder,"figure4", ncols = 2, nrows = 3, left=0.15, wspace=0.4)

        simulationList = ["Prognostic_48h", "ICE4_24h"]

        for k in simulationList:
            self.simulationCollection[k].getTSDataset()
            self.simulationCollection[k].getNCDataset()
            self.simulationCollection[k].setTimeCoordToHours()

        lwpYlimit = 60
        iwpYlimit = 21

        xPosition = 0.52
        yPositionFrac = 0.91

        # figA
        ax = fig.getAxes(0)
        for k in simulationList:
            Plot.getTimeseries(ax,
                           self.simulationCollection[k],
                           "lwp_bar", conversionFactor=1000.)
        end = lwpYlimit
        PlotTweak.setAnnotation(ax, "a) Liquid water path", xPosition=xPosition, yPosition= yPositionFrac*end)
        PlotTweak.setYaxisLabel(ax,"LWP", "g\ m^{-2}")
        PlotTweak.setYLim(ax, end = end)
        PlotTweak.setYLim(ax, end = end)
        ticks = PlotTweak.setYticks(ax, end = end, interval = 2)
        shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 10)
        PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        # figB
        ax = fig.getAxes(1)
        for k in simulationList:
            Plot.getTimeseries(ax,
                               self.simulationCollection[k],
                               "iwp_bar", conversionFactor=1000.)
        end = iwpYlimit
        PlotTweak.setAnnotation(ax, "b) Ice water path", xPosition=xPosition, yPosition= yPositionFrac*end)
        PlotTweak.setYaxisLabel(ax,"IWP", "g\ m^{-2}")
        PlotTweak.setYLim(ax, end = end)
        end = iwpYlimit
        PlotTweak.setYLim(ax, end = end)
        ticks = PlotTweak.setYticks(ax, end = end, interval = 1)
        shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 3)
        PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        # figC
        ax = fig.getAxes(2)
        for k in simulationList:
            self.simulationCollection[k].getNCDataset()["Ni_ii_vol"].plot(ax = ax,
                                                                     color = self.simulationCollection[k].getColor(),
                                                                     label =  self.simulationCollection[k].getLabel(),
                                                                     linewidth = self.simulationCollection[k].getLineWidth())
        end = 5
        PlotTweak.setAnnotation(ax, "c) Ice number \nconcentration", xPosition=xPosition, yPosition= 4)
        PlotTweak.setYaxisLabel(ax,"N_{i}", "L^{-1}")
        PlotTweak.setYLim(ax, end = end)
        ticks = PlotTweak.setYticks(ax, end = end, interval = 0.2, integer=False)

        shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 1)
        PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        # figD
        ax = fig.getAxes(3)
        for k in simulationList:
            Plot.getTimeseries(ax,
                               self.simulationCollection[k],
                               "Nc_ic", conversionFactor=1e-6)
        end = 170
        PlotTweak.setAnnotation(ax, "d) In-cloud CDNC", xPosition=xPosition, yPosition= yPositionFrac*end)
        PlotTweak.setYaxisLabel(ax,"CDNC", "mg^{-1}")
        PlotTweak.setYLim(ax, end = end)
        ticks = PlotTweak.setYticks(ax, end = end, interval = 10)
        shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 50)
        PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        # figE
        ax = fig.getAxes(4)
        for k in simulationList:
            for muuttuja in ["zb", "zc"]:
                self.simulationCollection[k].getTSDataset()[muuttuja].where(self.simulationCollection[k].getTSDataset()[muuttuja] > 0).plot(ax = ax,
                                                                     color = self.simulationCollection[k].getColor(),
                                                                     label =  self.simulationCollection[k].getLabel(),
                                                                     linewidth = self.simulationCollection[k].getLineWidth())
        end = 1000
        PlotTweak.setAnnotation(ax, "e) Cloud top and base", xPosition=xPosition, yPosition= yPositionFrac*end)
        PlotTweak.setYaxisLabel(ax,"Height", "m")
        PlotTweak.setYLim(ax, end = end)
        ticks = PlotTweak.setYticks(ax, end = end, interval = 100)
        shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 200)
        PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        for i in range(5):
            ax = fig.getAxes(i)
            end = 32
            PlotTweak.setXLim(ax, end = end)
            Plot.getVerticalLine(ax, 2)
            Plot.getVerticalLine(ax, 24)

            if i in [3,4]:
                PlotTweak.setXaxisLabel(ax,"Time", "h")
            else:
                PlotTweak.setXaxisLabel(ax,"")
                PlotTweak.hideXTickLabels(ax)

            ticks = PlotTweak.setXticks(ax, end = end, interval = 0.5)
            shownLabelsBoolean = PlotTweak.setXLabels(ax, ticks, end = end, interval = 4)
            PlotTweak.setXTickSizes(ax, shownLabelsBoolean)

        # empty space
        ax = fig.getAxes(5)
        ax.axis("off")
        legend_elements = [Patch(facecolor=self.simulationCollection["Prognostic_48h"].getColor(),
                             label='Prognostic ice'),
                       Patch(facecolor=self.simulationCollection["ICE4_24h"].getColor(),
                             label='ICE4')]

        ax.legend(handles=legend_elements, loc='center', frameon = True, framealpha = 1.0)

        fig.save()
コード例 #22
0
    def figure2(self):

        # create figure object
        fig = Figure(self.figurefolder,"figure2", ncols = 2, nrows = 3)

        simulationList = Figure2SimulationList()

        for k in simulationList.getAllSimulations():
            try:
                self.simulationCollection[k].getTSDataset()
                self.simulationCollection[k].setTimeCoordToHours()
            except FileNotFoundError:
                if "ovchinnikov" in str(self.simulationCollection[k].getFolder()).lower():
                    print("Ovchinnikov data is not available. Continue with existing simulations")
                    continue
                else:
                    print("{0} data missing from {1}, make sure you have set your \
                          folder and environment variables correctly".format(k, self.simulationCollection[k].getFolder()))

            if self.simulationCollection[k].getLabel() == "BULK":
                self.simulationCollection[k].setZorder(1)
            elif self.simulationCollection[k].getLabel() == "BIN":
                self.simulationCollection[k].setZorder(2)
            else:
                self.simulationCollection[k].setZorder(3)

        for k in simulationList.getUCLALESSALSASimulations():
            self.simulationCollection[k].setLineWidth(matplotlib.rcParams["lines.linewidth"]*1.5)
            self.simulationCollection[k].setColor(Colorful.getDistinctColorList("green"))

        lwpYlimit = 60
        iwpYlimit = 21
        yPositionFrac = 0.91

        # figA
        ax = fig.getAxes(0)
        for k in simulationList.getIce0Simulations():
            Plot.getTimeseries(ax,
                               self.simulationCollection[k],
                               "lwp_bar", conversionFactor=1000.)
        PlotTweak.setAnnotation(ax, "a) ICE0 liquid water path", xPosition=0.2, yPosition= lwpYlimit*yPositionFrac)

        # figB
        ax = fig.getAxes(2)
        for k in simulationList.getIce1Simulations():
            Plot.getTimeseries(ax,
                               self.simulationCollection[k],
                               "lwp_bar", conversionFactor=1000.)
        PlotTweak.setAnnotation(ax, "b) ICE1 liquid water path", xPosition=0.2, yPosition= lwpYlimit*yPositionFrac)

        # figC
        ax = fig.getAxes(3)
        for k in simulationList.getIce1Simulations():
            Plot.getTimeseries(ax,
                               self.simulationCollection[k],
                               "iwp_bar", conversionFactor=1000.)
        PlotTweak.setAnnotation(ax, "c) ICE1 ice water path", xPosition=0.2, yPosition= iwpYlimit*yPositionFrac)

        # figD
        ax = fig.getAxes(4)
        for k in simulationList.getIce4Simulations():
            Plot.getTimeseries(ax,
                               self.simulationCollection[k],
                               "lwp_bar", conversionFactor=1000.)
        PlotTweak.setAnnotation(ax, "d) ICE4 liquid water path", xPosition=0.2, yPosition= lwpYlimit*yPositionFrac)

        # figE
        ax = fig.getAxes(5)
        for k in simulationList.getIce4Simulations():
            Plot.getTimeseries(ax,
                               self.simulationCollection[k],
                               "iwp_bar", conversionFactor=1000.)
        PlotTweak.setAnnotation(ax, "e) ICE4 ice water path", xPosition=0.2, yPosition= iwpYlimit*yPositionFrac)

        for i in [0,2,4]: #LWP figures
            ax = fig.getAxes(i)
            end = lwpYlimit
            PlotTweak.setYaxisLabel(ax,"LWP", "g\ m^{-2}")
            PlotTweak.setYLim(ax, end = end)
            ticks = PlotTweak.setYticks(ax, end = end, interval = 2)
            shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 10)
            PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        for i in [1,3,5]: #IWP figures
            ax = fig.getAxes(i)
            PlotTweak.setYaxisLabel(ax,"IWP", "g\ m^{-2}")
            end = iwpYlimit
            PlotTweak.setYLim(ax, end = end)
            ticks = PlotTweak.setYticks(ax, end = end, interval = 1)
            shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 3)
            PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        for i in [0,2,3,4,5]: #all timeseries figures
            ax = fig.getAxes(i)
            end = 8
            PlotTweak.setXLim(ax, end = end)
            Plot.getVerticalLine(ax, 2)

            if i in [4,5]:
                PlotTweak.setXaxisLabel(ax,"Time", "h")
            else:
                 PlotTweak.setXaxisLabel(ax,"")
                 PlotTweak.hideXTickLabels(ax)

            ticks = PlotTweak.setXticks(ax, end = end, interval = 0.5, integer=False)
            ticks = [int(k) for k in  ticks]
            shownLabelsBoolean = PlotTweak.setXLabels(ax, ticks, end = end, interval = 2)
            PlotTweak.setXTickSizes(ax, shownLabelsBoolean)

        # empty space
        ax = fig.getAxes(1)
        ax.axis("off")
        legend_elements = [Patch(facecolor=self.simulationCollection["ICE0_8h"].getColor(),
                             label='UCLALES-SALSA'),
                       Patch(facecolor=self.simulationCollection["SAM-bin_ice0"].getColor(),
                             label='BIN'),
                       Patch(facecolor=self.simulationCollection["COSMO_ice0"].getColor(),
                             label='BULK')]

        ax.legend(handles=legend_elements, loc='center', frameon = True, framealpha = 1.0)

        fig.save()
コード例 #23
0
    def figure5(self):

        fig = Figure(self.figurefolder,"figure5", ncols = 2, nrows = 2, wspace=0.1, bottom = 0.14, left=0.15, top=0.98)

        simulation = "Prognostic_48h"

        self.simulationCollection[simulation].getPSDataset()
        self.simulationCollection[simulation].getTSDataset()
        self.simulationCollection[simulation].setTimeCoordToHours()

        logaritmicLevels = PlotTweak.getLogaritmicTicks(-17,-9, includeFives = True)
        end = 1000
        yPositionFrac = 0.9
        xPosition = 0.5
        orange = Colorful.getDistinctColorList("orange")

        annotation = ["a) Dust in aerosols", "b) Dust in cloud droplets", "c) Dust in ice crystals"]
        for ind, muuttuja in enumerate(["P_cDUa", "P_cDUc", "P_cDUi"]):
            ax = fig.getAxes(ind)
            data = self.simulationCollection[simulation].getPSDataset()[muuttuja]
            data.values  = numpy.log10(data.values)

            im = data.plot.contourf("time","zt", ax = ax, levels=logaritmicLevels, add_colorbar = False)
            self.simulationCollection[simulation].getTSDataset()["zb"].plot(ax = ax,
                                                                     color = orange,
                                                                     linewidth = self.simulationCollection[simulation].getLineWidth())

            ax = Plot.getContourLine(ax, self.simulationCollection[simulation], "P_RHi", 100)
            PlotTweak.setAnnotation(ax, annotation[ind], xPosition=xPosition, yPosition= yPositionFrac*end)

            end = 1000
            PlotTweak.setYLim(ax, end = end)
            ticks = PlotTweak.setYticks(ax, end = end, interval = 100)
            shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 200)
            PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        for i in range(3):
            ax = fig.getAxes(i)
            end = 33.05
            PlotTweak.setXLim(ax, end = end)
            Plot.getVerticalLine(ax, 2)

            if i in [1,2]:
                PlotTweak.setXaxisLabel(ax,"Time", "h")
            else:
                PlotTweak.setXaxisLabel(ax,"")
                PlotTweak.hideXTickLabels(ax)

            if i == 1:
                PlotTweak.hideYTickLabels(ax)

            if i in [0,2]:
                PlotTweak.setYaxisLabel(ax,"Height", "m")
            else:
                PlotTweak.setYaxisLabel(ax,"")
                PlotTweak.hideYTickLabels(ax)

            ticks = PlotTweak.setXticks(ax, end = end, interval = 1)
            shownLabelsBoolean = PlotTweak.setXLabels(ax, ticks, end = end, interval = 4)
            PlotTweak.setXTickSizes(ax, shownLabelsBoolean)


        # empty space
        ax = fig.getAxes(3)
        ax.axis("off")
        legend_elements = [Patch(facecolor="black",
                             label='RH over ice 100%'),
                       Patch(facecolor=orange,
                             label='Cloud base')]

        ax.legend(handles=legend_elements, loc=(0.07,-0.02), frameon = True, framealpha = 1.0)
        cax = matplotlib.pyplot.axes([0.6, 0.4, 0.33, 0.03])
        Plot.getColorBar(im,cax,logaritmicLevels)

        shownLabelsBoolean = Data.getMaskedList(logaritmicLevels, numpy.arange(-11,-19,-1))
        PlotTweak.hideLabels(cax.xaxis, shownLabelsBoolean)
        PlotTweak.setXTickSizes(cax, shownLabelsBoolean)
        PlotTweak.setXaxisLabel(cax, "", unit="kg\ kg^{-1}")
        ###
        fig.save()
コード例 #24
0
ファイル: Plot.py プロジェクト: JaakkoAhola/LES-03plotting
    def getTimeseriesOfBinMass(ax,
                               simulation: Simulation,
                               muuttuja,
                               height,
                               cmap="OrRd",
                               relative=True,
                               limiter=1e-3):

        ps = simulation.getPSDataset()

        if ps is None:
            return "FileNotFound"

        zt = ps.zt

        psSliced = ps.sel(zt=height,
                          method="nearest").isel(time=slice(61, 1440))
        try:
            data = psSliced[muuttuja]
        except KeyError:
            return

        aerosolsUsed = False
        AerosolAbins = False
        AerosolBbins = False
        parallelAeroB = None
        parallelAeroA = None
        ################################
        if muuttuja == "P_Naba":
            aerosolsUsed = True

            if muuttuja == "P_Naba":
                AerosolAbins = True
            elif muuttuja == "P_Nabb":
                AerosolBbins = True

        if aerosolsUsed:
            parallelCloudA = psSliced["P_Ncba"]
            parallelCloudB = psSliced["P_Ncbb"]
        if AerosolAbins:
            parallelAeroB = psSliced["P_Nabb"]

        elif AerosolBbins:
            parallelAeroA = psSliced["P_Naba"]

        biniTieto = muuttuja[-1].upper()
        ################################

        dataAllBins = data
        dataAllBins = dataAllBins.assign_coords(time=(dataAllBins.time / 3600))
        size = numpy.shape(dataAllBins.values)[1]
        colorpalette = seaborn.color_palette(cmap, 10)
        skip = 0
        aero = None
        includeOtherAero = False
        includeParallelOthercloud = False
        includeParallelCloud = True

        label = biniTieto + " bin |" + r"$N_0\ (\#/kg)$"

        legend_elements = [
            matplotlib.patches.Patch(facecolor="white", label=label)
        ]
        for bini in range(size):
            plottable = dataAllBins[:, bini]

            vertailuData = numpy.zeros(numpy.shape(plottable.values))

            if Data.isCloseToEpsilon(plottable, limiter):
                skip += 1
                continue

            if AerosolAbins:
                parallelBaeroBini = bini - 3
                parallelAcloudBini = bini - 3
                parallelBcloudBini = bini - 3

            elif AerosolBbins:
                parallelAaeroBini = bini + 3
                parallelAcloudBini = bini
                parallelBcloudBini = bini

            if aerosolsUsed:  # and (parallelbini >= 0):

                if includeOtherAero:
                    if AerosolAbins and parallelBaeroBini > 0:
                        aero = parallelAeroB[:, parallelBaeroBini]
                    elif AerosolBbins:
                        aero = parallelAeroA[:, parallelAaeroBini]

                    vertailuData = vertailuData + aero.values

                if includeParallelOthercloud:
                    if AerosolAbins and parallelBcloudBini > 0:
                        parallelOtherCloud = parallelCloudB[:,
                                                            parallelBcloudBini]

                    elif AerosolBbins and parallelAcloudBini > 0:
                        parallelOtherCloud = parallelCloudA[:,
                                                            parallelAcloudBini]

                    vertailuData = vertailuData + parallelOtherCloud.values

                if includeParallelCloud:
                    if AerosolAbins:
                        parallelCloud = parallelCloudA[:, parallelAcloudBini]
                    elif AerosolBbins:
                        parallelCloud = parallelCloudB[:, parallelBcloudBini]

                    vertailuData = vertailuData + parallelCloud.values

            denom = plottable.values + vertailuData
            plottable, lahtoarvo = Data.getRelativeChange(plottable,
                                                          denominator=denom,
                                                          limiter=limiter)

            color = Data.getColorBin(colorpalette, bini, plottable)
            plottable.plot(ax=ax, color=color)

            if lahtoarvo > 1000 or lahtoarvo < 0.1:
                label = '{0:8d}{1:11.1E}'.format(bini + 1, Decimal(lahtoarvo))
            else:
                label = '{0:8d}{1:11.1f}'.format(bini + 1, lahtoarvo)
            legend_elements.append(
                matplotlib.patches.Patch(facecolor=color, label=label))

        if skip == size:
            matplotlib.pyplot.close()
            return None

        #matplotlib.pyplot.axvline( 2, color = "k" , linestyle = "--" )

        #matplotlib.pyplot.legend()
        ax.legend(handles=legend_elements,
                  loc='best',
                  frameon=True,
                  framealpha=1.0)

        heightTosi = str(int(zt.sel(zt=height, method='nearest').values))
        matplotlib.pyplot.title("zt =" + heightTosi + "(m)")
        #    print(time.values)
        ax = PlotTweak.setXTicksLabelsAsTime(ax,
                                             plottable["time"].values,
                                             startPoint=8)

        #matplotlib.pyplot.ylim(0, 5)
        ax.set_yscale('log')

        return ax
コード例 #25
0
            self.simulationCollection[k].setTimeCoordToHours()

        lwpYlimit = 60
        iwpYlimit = 22

        xPosition = 0.5
        yPositionFrac = 0.92

        # figA
        ax = fig.getAxes(0)
        for k in simulationList:
            Plot.getTimeseries(ax,
                           self.simulationCollection[k],
                           "lwp_bar", conversionFactor=1000.)
        end = lwpYlimit
        PlotTweak.setAnnotation(ax, "a) Liquid water path", xPosition=xPosition, yPosition= yPositionFrac*end)
        PlotTweak.setYaxisLabel(ax,"LWP", "g\ m^{-2}")
        PlotTweak.setYLim(ax, end = end)
        PlotTweak.setYLim(ax, end = end)
        ticks = PlotTweak.setYticks(ax, end = end, interval = 2)
        shownLabelsBoolean = PlotTweak.setYLabels(ax, ticks, end = end, interval = 10)
        PlotTweak.setYTickSizes(ax, shownLabelsBoolean)

        # figB
        ax = fig.getAxes(1)
        for k in simulationList:
            Plot.getTimeseries(ax,
                               self.simulationCollection[k],
                               "iwp_bar", conversionFactor=1000.)
        end = iwpYlimit
        PlotTweak.setAnnotation(ax, "b) Ice water path", xPosition=5, yPosition= yPositionFrac*end)