Пример #1
0
    def __init__(self):
        import magic
        
        file_circle=utility.find_file('magic.circle')
        file_linux=utility.find_file('magic.linux')

        cache_circle=os.path.join(utility.config_dir,"magic.circle.cache")
        cache_linux=os.path.join(utility.config_dir,"magic.linux.cache")

        self.magic={}
        self.magic['circle']=magic.Magic(file_circle,cache_circle)
        self.magic['linux']=magic.Magic(file_linux,cache_linux)
Пример #2
0
def run_post(inp,outdir,descr):
    wd = path.join(outdir,path.splitext(path.basename(inp))[0])
    if descr!="": wd+='-'+descr
    print '\n'
    print '--------------------------------------------------------------------------------'
    print '-- RUNNING POSTPROCESSOR:',path.join(wd,'job.odb')
    print '--------------------------------------------------------------------------------'
    # Run the extraction.
    rootdir = os.getcwd()
    try:
        os.chdir(wd)
    except Exception:
        utility.print_error(sys.exc_info()[0],False)
        return 0
    tstart = time.time()
    script = utility.find_file('python/abq_extract_data.py')
    cmd=[ABAQUS,'cae','noGUI='+script,'--','job.odb','data.rpt']
    try:
        utility.run_cmd_screen(cmd)
        with open('data.tmp','w') as of, open('data.rpt','r') as f:
            for line in f:
                line = line.rstrip()    # Remove newline/carriage-return.
                if line.find('NoValue') < 0: of.write(line+'\n')
        shutil.move('data.tmp','data.rpt')
    except Exception:
        utility.print_error(sys.exc_info()[0],False)
        print 'TIME ELAPSED: ',utility.time_elapsed(tstart)
        os.chdir(rootdir)
        return 0
    try:
        import create_result_plots, numpy
        from matplotlib import pyplot
        pyplot.rc('mathtext',default='regular') # Don't use italics for mathmode.
        fig,ax = pyplot.subplots()
        create_result_plots.plot_fem_data(ax,'data.rpt')
        lgd = ax.legend(loc='best',frameon=False,framealpha=0)
        pyplot.savefig('plot.png',bbox_extra_artists=(lgd,), bbox_inches='tight')
        pyplot.close()
        if path.exists('data-energy.rpt'):
            fig,ax = pyplot.subplots()
            create_result_plots.plot_fem_energy(ax,'data-energy.rpt')
            lgd = ax.legend(loc='best',frameon=False,framealpha=0)
            pyplot.savefig('plot-energy.png',bbox_extra_artists=(lgd,), bbox_inches='tight')
            pyplot.close()
        if path.exists('data-strain.csv'):
            fig,ax = pyplot.subplots()
            data = numpy.loadtxt('data-strain.csv',delimiter=',')
            ax.plot(data[:,0],data[:,1],'o-',label='Nominal Strain')
            ax.set_xlabel('Time (meaningless units)')
            ax.set_ylabel('Nominal Strain')
            ax.grid()
            pyplot.savefig('plot-strain.png', bbox_inches='tight')
            pyplot.close()
    except Exception:
        utility.print_error('Failed to create result plots.',False)
    print 'TIME ELAPSED: ',utility.time_elapsed(tstart)
    os.chdir(rootdir)
    return 1
Пример #3
0
def analyze(title):
    song = find_file(title)
    npz = retrieve_segments(song)
    segments, name = npz.values()
    name = np.asscalar(name)
    seg0 = segments[0]

    chroma_path = api.save_plot_chroma(seg0, name)
    tempo_path = api.save_plot_tempo(seg0, name)
    audio_path = api.save_segment(seg0, name)

    return flask.render_template('analyze.html',
                                 name=name,
                                 audio_path=audio_path,
                                 chroma_path=chroma_path,
                                 tempo_path=tempo_path)
Пример #4
0
            # Length constraints.
            if np.diff(args.length_constraints)!=0.0:
                Lmax = lambda P: args.length_constraints[1] - calc_nc(P[0],popt[0])*P[5] - (calc_nc(P[0],popt[0])+1)*P[6]
                Lmin = lambda P: calc_nc(P[0],popt[0])*P[5] + (calc_nc(P[0],popt[0])+1)*P[6] - args.length_constraints[0]
                constraints.append({'type': 'ineq', 'fun': Lmax})
                constraints.append({'type': 'ineq', 'fun': Lmin})
            # Width constraints.
            if np.diff(args.width_constraints)!=0.0:
                Wmax = lambda P: args.width_constraints[1] - P[4] - 2.0*P[6]
                Wmin = lambda P: P[4] + 2.0*P[6] - args.width_constraints[0]
                constraints.append({'type': 'ineq', 'fun': Wmax})
                constraints.append({'type': 'ineq', 'fun': Wmin})
        # Other variables.
        act = args.actuator
        matfile = path.abspath(args.matfile)
        script = path.abspath(U.find_file('python/abq_create_geom.py'))
        geomcmd = ['abaqus', 'cae', 'noGUI='+script,'--',
                   'test_geo-'+act+args.test+'.cae', 'noale', act,
                   args.test, args.mesh_size, '0.05',
                   str(args.time), str(args.num_chambers), '1wall',
                   str(args.inlet[0]), str(args.inlet[1]),
                   str(args.chamber[0]), str(args.chamber[1]), str(args.chamber[2]),
                   str(args.wall), '1.0', matfile, 'none',
                   str(args.dist_to_force), str(args.maxnuminc)]
        # This lambda function will end up taking simply the iteration and the optimization parameters.
        optfunc = lambda Rargs: run_multiACT(act,args.test,args.dist_to_force,geomcmd,pressures,
                                             args.num_chambers,*Rargs)

    #--------------------------------------------------------------------------------
    # Change directory.
    #--------------------------------------------------------------------------------
Пример #5
0
def run_slurm(inp, cp, time, outdir, nn, np, descr):
    outdir = path.abspath(outdir)
    dirname = path.splitext(path.basename(inp))[0]
    if descr != "": dirname += '-' + descr
    wd = path.join(outdir, dirname)
    if wd.startswith('/home'):
        print 'ERROR: /home is readonly during execution, use /scratch.'
        return 0, ''
    if path.exists(wd): shutil.rmtree(wd)
    if not inp.endswith('.inp'):
        utility.print_error('Input file must be a .inp Abaqus run file.',
                            False)
        return 0, ''
    # Prepare the directories.
    os.makedirs(wd)
    shutil.copyfile(inp, path.join(wd, 'job.inp'))
    create_env(np, wd, nn)
    # Create the submission script.
    extfile = path.abspath(utility.find_file('python/abq_extract_data.py'))
    jobfile = path.join(wd, dirname + '.job')
    runcmd = ABAQUS + ' job=job input=job.inp interactive'
    postcmd = ABAQUS + ' cae noGUI=' + extfile + ' -- job.odb data.rpt'
    # TODO - need ability to set email address here.
    with open(jobfile, 'w') as f:
        f.write('''#!/bin/bash
# mem directive is per node.
#SBATCH --nodes ''' + str(nn) + '''
#SBATCH --cpus-per-task 1
#SBATCH --ntasks-per-node ''' + str(np) + '''
#SBATCH --mem ''' + str(cp['mem'] * np / cp['np']) + '''
#SBATCH --time ''' + time + '''
#SBATCH --workdir ''' + wd + '''
#SBATCH --mail-type=END
#SBATCH --mail-type=FAIL
#SBATCH [email protected]
#SBATCH --share
''')
        f.write(cp['modules'])
        f.write(
            '''echo '**********************************************************************'
echo 'Starting execution at' `date`
echo 'Job script:' $0
''')
        if nn != 1:
            f.write('''
scontrol show hostname $SLURM_JOB_NODELIST | paste -d -s > hostlist
HLIST="["
for i in $(cat hostlist)
do
HLIST="$HLIST['$i',''' + str(np) + '''],"
done
HLIST=`echo $HLIST | sed -e "s/,$/]/"`
echo "mp_host_list=$HLIST" >> abaqus_v6.env
echo "Hostlist: $HLIST"
''')
        f.write(
            '''echo '**********************************************************************'
''' + runcmd + '''
sleep 5
echo
echo '**********************************************************************'
echo 'Running postprocessor.'
echo '**********************************************************************'
''' + postcmd + '''
echo
echo 'Finished execution at' `date`
echo " ****** END OF JOB ******"''')
    return 1, jobfile
    # TODO - smooth dataset?

    # Prep variables.
    matfile = path.abspath(args.matfile)
    max_strain = max(data[:, 1])
    A = float(args.dims[0]) * float(args.dims[1])
    L = float(args.dims[2])  # Divided by two later, in abq_hysttest.py
    time = L * max_strain / args.rate

    # Change directory.
    if path.exists(args.dirname):
        U.print_error('Output directory exists.', True)
    os.makedirs(args.dirname)
    rootdir = os.getcwd()
    os.chdir(args.dirname)
    script = U.find_file('python/abq_hysttest.py')

    # Calculate optimal parameters.
    print '---------------------------------------------------------'
    print ' Calculating parameters...'
    cmd0 = [
        'abaqus', 'cae', 'noGUI=' + script, '--', matfile, args.dims[0],
        args.dims[1], args.dims[2],
        str(max_strain),
        str(time)
    ]
    maxitr = 1000
    popt = [1.6, 0.5, 4.0, -1.0]
    min_fun = lambda args: fit_error(data, cmd0, A, L, *args)
    OR = opt.minimize(min_fun,
                      popt,
Пример #7
0
        help='Approximate size of mesh elements (default 2.0).')

    args = parser.parse_args()

    #------------------------------------------------------------------------------------
    # Prep the arguments.
    #------------------------------------------------------------------------------------
    # Create the directory, if necessary.
    caedir = path.split(args.cae)[0]
    if caedir == '': caedir = os.getcwd()
    elif not os.path.exists(caedir): os.makedirs(caedir)
    # If the cae file already exists, remove it because Abaqus won't necessarily overwrite it.
    if path.isfile(args.cae): os.remove(args.cae)
    # Change directory, since Abaqus is limited in where it can write files.
    if args.cmd == 'actuator':
        acg_file = utility.find_file('python/abq_create_geom.py')
    elif args.cmd == 'bubble':
        acg_file = utility.find_file('python/abq_create_bubble.py')
    rootdir = os.getcwd()
    os.chdir(caedir)
    acg_file = path.normpath(path.join(rootdir, acg_file))
    cae_file = path.split(args.cae)[1]
    inp_file = path.splitext(cae_file)[0] + '.inp'
    mat_file = path.normpath(path.join(rootdir, args.matfile))
    if args.cmd == 'actuator':
        vis_file = path.normpath(path.join(
            rootdir, args.visco)) if args.visco != 'none' else 'none'

    #------------------------------------------------------------------------------------
    # Linear and bending actuators.
    #------------------------------------------------------------------------------------