Esempio n. 1
0
File: process.py Progetto: rc/elfpy
def read_all_data(filenames, options):
    directory = op.split(__file__)[0]
    areas = read_file_info(op.join(directory, options.cross_sections_filename))
    lengths = read_file_info(op.join(directory, options.init_lengths_filename))

    datas = []
    cols = options.columns
    for i_file, filename in enumerate(filenames):
        data = Data.from_file(filename, sep=options.separator,
                              icycles=cols.get('cycle', None),
                              itime=cols.get('time', 2),
                              idispl=cols.get('displ', 1),
                              iforce=cols.get('force', 0))
        data.set_initial_values(lengths=lengths, areas=areas)
        datas.append(data)

    return datas
Esempio n. 2
0
def main():
    """
    The following command line options are available:

    - def_ss : the final value of strain for small deformations
    - def_ls : the interval of strain for large deformations
    - legend_fontsize : a font size of the legends
    - file_name_out : output file name
    - one_cycle : data contain only one cycle
    - cycles : data contain only cycles
    - cut_first_cycle : the first cycle will be cut from the evaluation
    - s : save the pictures with evaluated curves and files with mechanical
      properties
    - mean_val : count the mean value of moduli of elasticity of all inserted
      stress-strain curves
    - cut_strain : cut the region of defined strain
    - ultim_val : get ultimate values of stress and strain
    - sampling : the sampling interval
    - sensitivity : the sensitivity of approximation
    - conf : use configuration file
    - mean_plot : plot the mean stress-strain curve
    """

    parser = OptionParser(usage=usage, version="%prog ")
    parser.add_option("", "--def-ss", type=float, metavar='float',
                      action="store", dest="def_ss",
                      default=None, help=help['def_ss'])
    parser.add_option("", "--def-ls", type='str', metavar='float,float',
                      action="callback", dest="def_ls",
                      callback=parse_def_ls, help=help['def_ls'])
    parser.add_option("-o", "", metavar='string',
                      action="store", dest="file_name_out",
                      default=None, help=help['file_name_out'])
    parser.add_option("", "--legend-fontsize", type=int, metavar='int',
                      action="store", dest="legend_fontsize",
                      default=None, help=help['legend_fontsize'])
    parser.add_option("", "--one-cycle",
                      action="store_true", dest="one_cycle",
                      default=None, help=help['one_cycle'])
    parser.add_option("", "--cycles",
                      action="store_true", dest="cycles",
                      default=None, help=help['cycles'])
    parser.add_option("", "--cut-first-cycle",
                      action="store_true", dest="cut_first_cycle",
                      default=None, help=help['cut_first_cycle'])
    parser.add_option("-s", "",
                      action="store_true", dest="s",
                      default=None, help=help['s'])
    parser.add_option("", "--mean-val",
                      action="store_true", dest="mean_val",
                      default=None, help=help['mean_val'])
    parser.add_option("", "--cut-strain", type=float, metavar='float',
                      action="store", dest="cut_strain",
                      default=None, help=help['cut_strain'])
    parser.add_option("", "--ultim-val",
                      action="store_true", dest="ultim_val",
                      default=None, help=help['ultim_val'])
    parser.add_option("", "--sampling", type=int, metavar='int',
                      action="store", dest="sampling",
                      default=None, help=help['sampling'])
    parser.add_option("", "--sensitivity", type=float, metavar='float',
                      action="store", dest="sensitivity",
                      default=None, help=help['sensitivity'])
    parser.add_option("-c", "--conf", metavar='filename',
                      action="store", dest="conf_filename",
                      default=None, help=help['conf_filename'])
    parser.add_option("", "--mean-plot",
                      action="store_true", dest="mean_plot",
                      default=None, help=help['mean_plot'])
    cmdl_options, args = parser.parse_args()

    expanded_args = []
    for arg in args:
        expanded_args.extend(glob.glob(arg))
    args = expanded_args

    file_number = len(args)
    if file_number == 0:
        parser.print_help()
        return

    can_override = set()
    for key, default in default_options.iteritems():
        val = getattr(cmdl_options, key)
        if val is None:
            setattr(cmdl_options, key, default)
        else:
            can_override.add(key)

    if cmdl_options.conf_filename is not None:
        config = Config.from_file(cmdl_options.conf_filename,
                                  defaults=default_options)
    else:
        conf = {'options' : {'default' : default_options},
                'options_default' : default_options}
        config = Config.from_conf(conf)

    config.override(cmdl_options, can_override)
    options = Object(name='options', **(config.options['default']))

    filename_out = options.file_name_out

    markers, linestyles, color_vector = define_plot_attributes()

    fp = fm.FontProperties()
    fp.set_size(options.legend_fontsize)

    directory = op.split(__file__)[0]

    areas = read_file_info(op.join(directory,'cross_sections.txt'))
    lengths = read_file_info(op.join(directory,'init_lengths.txt'))

    isFinal = False
    isLast = False
    isPlot = 0


    if not options.one_cycle:
        p.figure(1)
        p.clf()
    if not options.cycles:
        p.figure(5)
        p.clf()


    all_fits = {}
    list_fits = []
    ks = []
    h_datas = []
    ult_strain=[]
    ult_stress=[]
    strain_all = []
    stress_all = []
    strain_size = []
    k_fig = 5
    for i_file in range( 0, file_number ):
        filename = args[i_file]
        print 'file:', filename

        if filename in config.options:
            specific_options = Object(name='options', **(config.options[filename]))
        else:
            specific_options = options

        fits, strain, stress = fit_data(filename, specific_options, lengths, areas,
                                               isPlot = isPlot )
        if specific_options.mean_plot:
            strain_size.append(strain.shape[0])
            strain_all.append(strain)
            stress_all.append(stress)
            print 'strain_all', strain_all, strain_size

        if not specific_options.cycles:
            k0, k1, h_fit, h_data = fit_stress_strain_lines(k_fig, filename, strain,
                                                                   stress, specific_options, i_file,
                                                                   color_vector, markers,
                                                                   isPlot = isPlot )
            ks.append( (k0, k1) )
            h_datas.extend(h_data)

            if options.ultim_val:
                ultim_strain, ultim_stress = get_ultimate_values(strain, stress)
                ult_strain.append(ultim_strain)
                ult_stress.append(ultim_stress)

        if i_file == 0:
            avg_fits = np.zeros_like(fits)
        avg_fits += fits
        all_fits[filename] = fits
        list_fits.append(fits)
    avg_fits /= float(file_number)

    if specific_options.mean_plot:
        index_length = np.min(strain_size)
        print index_length
        strain_mean = np.mean(strain_all, 0)
        stress_mean = np.mean(stress_all, 0)
        p.figure(61)
        p.plot(strain_mean, stress_mean, marker = 'p', color = 'k')

    if options.ultim_val:
        ult_strain = np.array(ult_strain, dtype = np.float64)
        ult_strain_average = np.sum(ult_strain, 0) / ult_strain.shape[0]
        ult_strain_dev = np.std(ult_strain, 0)
        print 'ultimate_strain', ult_strain_average, '\pm', ult_strain_dev

        ult_stress = np.array(ult_stress, dtype = np.float64)
        ult_stress_average = np.sum(ult_stress, 0) / ult_stress.shape[0]
        ult_stress_dev = np.std(ult_stress, 0)
        print 'ultimate_stress', ult_stress_average, '\pm', ult_stress_dev



    list_fits.insert(0, avg_fits)
    a_fits = np.array(list_fits, dtype = np.float64).T
    print a_fits.shape
    if options.s:
        print 'output file:', filename_out

        fd = open(op.splitext( filename_out)[0] + '_moduli_cycles.txt',
                        'w' )
        for row in a_fits:
            fd.write(' '.join([('%.3e' % ii) for ii in row]))
            fd.write('\n')
        fd.close()

    if not options.cycles:
        if options.mean_val:
            ks = np.array(ks, dtype = np.float64)
            ks_average = np.sum(ks, 0) / ks.shape[0]
            ks_dev = np.std(ks, 0)
            print ks
            print ks_average
            print ks_dev
            if options.s:
                np.savetxt(op.splitext( filename_out )[0] + '_moduli.txt', ks)

            fig = p.figure(k_fig)
            p.xlabel( 'strain' )
            p.ylabel( 'stress [MPa]' )
            texts = [r'$E_0 = %.2e\ \pm\ %.2e$' % (ks_average[0], ks_dev[0]),
                    r'$E_1 = %.2e\ \pm\ %.2e$' % (ks_average[1], ks_dev[1])]
            leg = make_legend_text(args, ks)
            fig.legend(h_datas, leg, loc = (0.6, 0.35), prop=fp)
            p.legend(h_fit, texts, loc = 'lower right', prop=fp)

            if options.s:
                fig_name = op.splitext(filename_out )[0] + '_stress_strain.pdf'
                p.savefig(fig_name, dpi = 300)
        else:
            ks = np.array(ks, dtype = np.float64)
            print ks
            if options.s:
                np.savetxt(op.splitext(filename_out)[0] + '_moduli.txt', ks)
            p.figure(k_fig)

            leg = make_legend_text(args, ks)
            p.xlabel( 'strain' )
            p.ylabel( 'stress [MPa]' )
            p.legend(h_datas, leg, loc = 'upper right', prop=fp)
            if options.s:
                fig_name = op.splitext(filename_out)[0] + '_stress_strain.pdf'
                p.savefig(fig_name, dpi = 300)

    if isLast:
        to = avg_fits.shape[0]
    else:
        to = avg_fits.shape[0] - 1

    if not options.one_cycle:
        p.figure( 1 )
        cycle = np.arange( 1, to + 1 )
        if not isFinal:
            leg = []
            ii=0
            for name, fits in all_fits.iteritems():
                p.plot(cycle, fits[:to], color=color_vector[ii,:3], marker=markers[ii], markersize = 3, label=op.splitext(name)[0])
                ii=ii+1
            if options.mean_val:
                p.plot(cycle, avg_fits[:to], 'ro')
            else:
                pass
        if options.mean_val:
            p.errorbar(cycle, avg_fits[:to],
                    yerr = np.std(a_fits[:to,1:], 1),
                    marker = 'o', mfc = 'red', label='mean_value $\pm$ SD')
        else:
            pass

        p.legend(loc = 'upper right' , prop=fp)
        p.xlim(0, a_fits.shape[0] + 1)
        p.xlabel('cycle number')
        p.ylabel('modulus of elasticity [MPa]')

    if options.s:
        if isFinal:
            fig_name = op.splitext(filename_out)[0] + '.pdf'
        else:
            fig_name = op.splitext(filename_out)[0] + '_all.pdf'
        p.savefig(fig_name, dpi = 300)
    p.show()