예제 #1
0
파일: plot.py 프로젝트: stjordanis/openfdm
def command_line():
    import argparse

    argparser = argparse.ArgumentParser()
    argparser.add_argument("result", help="the result.mat file")
    args = argparser.parse_args()

    matFile = DyMatFile(os.path.abspath(args.result))
    x = matFile.data('p.r_r[1]')
    z = matFile.data('p.r_r[3]')

    ax = plt.subplot(111)
    formatter = EngFormatter(unit='m', places=1)
    ax.xaxis.set_major_formatter(formatter)
    ax.yaxis.set_major_formatter(formatter)
    ax.plot(x, -z)
    plt.xlabel('x')
    plt.ylabel('-z')
    plt.title('trajectory of ' + args.result)
    plt.grid()
    plt.show()
예제 #2
0
파일: plot.py 프로젝트: arktools/openfdm
def command_line():
  import argparse

  argparser = argparse.ArgumentParser()
  argparser.add_argument("result",
      help="the result.mat file")
  args = argparser.parse_args()

  matFile = DyMatFile(os.path.abspath(args.result))
  x = matFile.data('p.r_r[1]');
  z = matFile.data('p.r_r[3]');

  ax = plt.subplot(111)
  formatter = EngFormatter(unit='m', places=1)
  ax.xaxis.set_major_formatter(formatter)
  ax.yaxis.set_major_formatter(formatter)
  ax.plot(x, -z)
  plt.xlabel('x')
  plt.ylabel('-z')
  plt.title('trajectory of ' + args.result)
  plt.grid()
  plt.show()
예제 #3
0
        Parts.RigidLink_B321 t(
          angles={{ {motorAngle}, {motorAngle}, {motorAngle} }},
          r_a={{ {motorX}, {motorX}, {motorX} }});
      equation
        connect(p.fA,structure.fA);
        connect(structure.fA,t.fA);
        connect(t.fB,motor.fA);
      end Rocket;
    ")""".format(**val_dict))

        result = shell.execute(
            "simulate(Rocket,stopTime=1,numberOfIntervals=1000)")
        resultFile = get(result, "SimulationResults.resultFile")[1:-1]
        resultFile = os.path.splitext(resultFile)[0]

        matFile = DyMatFile(resultFile)
        timeTillFailure[motorXIndex][motorAngleIndex] = matFile.abscissa(
            'p.r_r[1]', valuesOnly=True)[-1]
        x = matFile.data('p.r_r[1]')
        y = matFile.data('p.r_r[2]')
        agl = matFile.data('p.agl')

        fig1 = plt.figure()
        a1 = fig1.add_subplot(111)
        a1.set_title('x: {motorX}, angle: {motorAngle}'.format(**val_dict))
        a1.set_xlabel('x')
        a1.set_ylabel('agl')
        a1.xaxis.set_major_formatter(formatter_m)
        a1.yaxis.set_major_formatter(formatter_m)
        a1.plot(x, agl)
        a1.grid()
예제 #4
0
    def generate_sigmoid(self):
        fig, ax = plt.subplots()

        X = np.arange(1, 101, 1, dtype=np.int32)
        A = []
        B = []
        C = []
        D = []

        T_s_pred = []

        for i in range(self.df_T_s.shape[0]):
            T_s = self.df_T_s.iloc[i].to_numpy()

            #Plot true data
            ax.plot(X, T_s, label="True", c="Black", marker="o")

            #Regression
            inputs = {"Temperatures": T_s, "num_discretisation": self.N_f}
            '''
            https://stackoverflow.com/questions/43213069/fit-bipolar-sigmoid-python
            General sigmoid function
            a adjusts amplitude : T_max
            b adjusts y offset  : T_min
            c adjusts x offset  : the smaller the c, the more sigmoid moves to the right
            d adjusts slope 
            '''
            a, b, c, d = fit_sigmoid.fit(inputs)
            A.append(a)
            B.append(b)
            C.append(c)
            D.append(d)

            T_s_fit = fit_sigmoid.sigmoid(X, (a, b, c, d))

            T_s_pred.append([val for val in T_s_fit])

            #Plot true fit
            ax.plot(X, T_s_fit, label="Fitted", c="Red", ls="--", marker="^")

            ax.set_xlabel("Dimensionless position [x/L]")
            ax.set_ylabel("Filler Temperature [K]")
            ax.set_ylim(500 + 273.15, 730 + 273.15)
            ax.set_xlim(1, 101)

            ax.set_title(
                "Regression vs True Filler Temp. Data no %s from %s data" %
                (i, self.df_T_s.shape[0]))
            ax.legend()

            plt.pause(0.0001)
            ax.cla()

        plt.show()

        T_s_pred = np.array(T_s_pred)
        print(T_s_pred.shape)

        if T_s_pred.shape[1] != self.N_f:
            #Transpose
            T_s_pred = T_s_pred.T

        self.df_T_s_pred = pd.DataFrame(
            T_s_pred,
            columns=[
                "T_s_%s_pred" % (index) for index in range(1, self.N_f + 1)
            ])

        self.df_sigmoid_param = pd.DataFrame(
            zip(A, B, C, D), columns=["T_max", "T_min", "Offset", "slope"])

        self.df_final = pd.concat(
            (self.df, self.df_T_s, self.df_T_s_pred, self.df_sigmoid_param),
            axis=1)

        return self.df_final
예제 #5
0
파일: trans.py 프로젝트: choeger/recon
def dsres2meld(df, mfp, verbose=False, compression=True, single=True):
    """
    This function reads in a file in 'dsres' format and then writes it
    back out in meld format.  Note there is a dependency in this code
    on numpy and dymat.
    """
    import numpy
    from DyMat import DyMatFile

    # Read dsres file
    mf = DyMatFile(df)
    # Open a meld file to write to
    meld = MeldWriter(mfp, compression=compression, single=single)

    # Initialize a couple of internal data structures
    tables = {}
    signal_map = {}
    alias_map = {}

    # This is the key to use for "description" fields
    DESC = "desc"

    # We loop over the blocks in the dsres file and each block
    # will end up being a table.
    for block in mf.blocks():
        # Extract the abscissa data for this block
        if verbose:
            print "Block: "+str(block)
        (abscissa, aname, adesc) = mf.abscissa(block)

        # Determine all columns in the dsres file and associate
        # the signals and aliases with these columns
        columns = {}
        if verbose:
            print "Abscissa: "+str(aname)+" '"+adesc+"'"

        signals = []
        aliases = []

        # Loop over all variables in this block and either make them
        # signals or aliases (if some other variable has already
        # claimed that column)
        for name in mf.names(block):
            col = mf._vars[name][2]
            if col in columns:
                if verbose:
                    print "  Alias "+name+" (of: "+columns[col]+")"
                aliases.append((name, mf._vars[name][0],
                                columns[col], mf._vars[name][3]))
            else:
                if verbose:
                    print "  Signal "+name+" ("+str(col)+")"
                columns[col] = name
                signals.append(name)

        if verbose:
            print "Number of columns: "+str(len(columns.keys()))
            print "Number of signals: "+str(len(signals))
            print "Number of aliases: "+str(len(aliases))

        signal_map[block] = signals
        alias_map[block] = aliases

        # Generate table for this block (and store it away for later)
        tables[block] = meld.add_table("T"+str(block))

        # Add abscissa
        tables[block].add_signal(aname, metadata={DESC: adesc})

        for signal in signals:
            tables[block].add_signal(signal, metadata={DESC: mf.description(signal)})

        # Add aliases (and their metadata)
        for alias in aliases:
            transform = None
            if alias[3]<0.0:
                tables[block].add_alias(alias=alias[0], of=alias[2],
                                        transform="aff(-1,0)",
                                        metadata={DESC:mf.description(alias[0])})
            else:
                tables[block].add_alias(alias=alias[0], of=alias[2],
                                        metadata={DESC:mf.description(alias[0])})

    # Finalize structure
    meld.finalize()

    # Now loop again, this time with the intention to write data
    for block in mf.blocks():
        # Write abscissa for this block
        (abscissa, aname, adesc) = mf.abscissa(block)
        abscissa = list(abscissa.astype(numpy.float))
        tables[block].write(aname, list(abscissa))

        signals = signal_map[block]

        # Then write signals (no need to write aliases)
        for signal in signals:
            vec = list(mf.data(signal).astype(numpy.float))
            tables[block].write(signal, vec)

    # Close the MeldWriter
    meld.close()
예제 #6
0
          r_a={{ {motorX}, {motorX}, {motorX} }});
      equation
        connect(p.fA,structure.fA);
        connect(structure.fA,t.fA);
        connect(t.fB,motor.fA);
      end Rocket;
    ")""".format(
                **val_dict
            )
        )

        result = shell.execute("simulate(Rocket,stopTime=1,numberOfIntervals=1000)")
        resultFile = get(result, "SimulationResults.resultFile")[1:-1]
        resultFile = os.path.splitext(resultFile)[0]

        matFile = DyMatFile(resultFile)
        timeTillFailure[motorXIndex][motorAngleIndex] = matFile.abscissa("p.r_r[1]", valuesOnly=True)[-1]
        x = matFile.data("p.r_r[1]")
        y = matFile.data("p.r_r[2]")
        agl = matFile.data("p.agl")

        fig1 = plt.figure()
        a1 = fig1.add_subplot(111)
        a1.set_title("x: {motorX}, angle: {motorAngle}".format(**val_dict))
        a1.set_xlabel("x")
        a1.set_ylabel("agl")
        a1.xaxis.set_major_formatter(formatter_m)
        a1.yaxis.set_major_formatter(formatter_m)
        a1.plot(x, agl)
        a1.grid()
        plt.savefig("fig/rocket-2d-{motorAngle}-{motorX}.pdf".format(**val_dict))
예제 #7
0
 def acquire_result(self, result_id=None):
     """Loads the result file dropped by the executable"""
     if result_id is None:
         result_id = self.result_tag
     return DyMatFile(self.get_result_path(result_id))