示例#1
0
 def __init__(self, port=None):
     if port is None:
         filedialogs.load_filename('Select a serial device',
                                   directory='/dev/serial/by-id/',
                                   file_filter=None)
     super().__init__(port)
     self.read_all()
示例#2
0
def load_mesh_constraints(op_filename=None,directory='/home/ppzmis/Documents/PythonScripts/FEM'):
    if op_filename is None:
        op_filename = load_filename(directory=directory, file_filter='*.h5')
    hf = h5py.File(op_filename, 'r')
    known_displacements = hf.get('displacements')
    known_forces = hf.get('forces')
    return known_displacements, known_forces
示例#3
0
    def __init__(self,
                 filename=None,
                 mpp=1,
                 fps=30.0,
                 rad=None,
                 max_lag=100,
                 temp=293):
        '''

        :param filename: DataStore filename
        :param mpp: microns per pixel
        :param fps: frames per second of movie
        :param rad: radius of particles in microns
        :param max_lag: maximum lag time in seconds - NB this is different to trackpy which measures this in frames
        :param temp: temperature of experiment

        All output quantities such as emsd and creep are in microns and seconds.
        Creep in SI.

        '''
        if filename is None:
            filename = load_filename(file_filter='*.hdf5')
        self.filename = filename
        self.data = dataframes.DataStore(filename)
        self.df = self.data.df
        self.df_subset = self.df.copy()

        self.mpp = mpp
        self.fps = fps
        self.rad = rad
        self.max_lag = int(max_lag * fps)
        self.temp = temp
示例#4
0
 def __init__(self,filename=None):
     '''
     Initialise video reading object
     if filename = None user must select filename with dialogue
     '''
     if filename == None:
         filename = fd.load_filename(caption='select movie filename', file_filter='*.avi;;*.mp4;;*.*')
     self.filename = filename
     self.open_video()
     self.get_vid_props()
示例#5
0
    def load_config(self, filename=None, parent=None):
        if filename is None:
            filename = load_filename(directory=self.cam_config_dir,
                                     file_filter='*.ccf',
                                     parent=parent)
        self.cam_dict = load_dict_from_file(filename)
        self._load_cam_config()
        SISO.Fg_loadConfig(self.fg, filename[:-3] + 'mcf')

        print('new config loaded')
示例#6
0
def calculate_corr_data(file=None, rmin=1, rmax=20, dr=0.02):
    if file is None:
        file = filedialogs.load_filename()
    new_file = file[:-5] + '_corr.hdf5'
    if not os.path.exists(new_file):
        data = dataframes.DataStore(file)
        calc = statistics.PropertyCalculator(data)
        res = calc.correlations_all_duties(rmin, rmax, dr)
        res = res.reset_index()
        res.to_hdf(new_file, 'df')
    else:
        print('file already exists')
示例#7
0
def load_mesh_from_file(filename=None,directory='/home/ppzmis/Documents/PythonScripts/FEM'):
    if filename is None:
        filename=load_filename(directory=directory,file_filter='*.h5')
    hf = h5py.File(filename, 'r')
    
    node_pts = np.array(hf.get('node_pts'))
    elements = np.array(hf.get('elements'))
    if 'vals' in hf.keys():
        values = np.array(hf.get('vals'))
    else:
        values = np.ones(np.shape(elements)[0])
    
    return (node_pts,elements,values)
示例#8
0
 def __init__(self, filename=None, grayscale=False, return_function=None):
     '''
     Initialise video reading object
     if filename = None user must select filename with dialogue
     '''
     if filename is None:
         filename = fd.load_filename(
             caption='select movie filename',
             file_filter='*.avi;;*.MP4;;*.mp4;;*.tif;;*.*')
     self.filename = filename
     self.grayscale = grayscale
     self.return_func = return_function
     self._detect_file_type()
     self.open_video()
     self.get_vid_props()
示例#9
0
    def load_cam_settings(self, filename=None):
        if filename is None:
            filename = load_filename(file_filter='*.camlog')

        with open(filename, 'r') as settings_file:
            settings_list = settings_file.read().splitlines()
        self.brightness = settings_list[0]
        self.contrast = settings_list[1]
        self.gain = settings_list[2]
        self.saturation = settings_list[3]
        self.hue = settings_list[4]
        self.exposure = settings_list[5]

        self.set_cam_props('brightness', self.brightness)
        self.set_cam_props('contrast', self.contrast)
        self.set_cam_props('gain', self.gain)
        self.set_cam_props('saturation', self.saturation)
        self.set_cam_props('hue', self.hue)
        self.set_cam_props('exposure', self.exposure)
示例#10
0
    -------
    ing: annotated image
        Same shape and type as input image
    """
    voro = sp.Voronoi(points)
    ridge_vertices = voro.ridge_vertices
    new_ridge_vertices = []
    for ridge in ridge_vertices:
        if -1 not in ridge:
            new_ridge_vertices.append(ridge)
    img = draw_polygons(img, voro.vertices[new_ridge_vertices], color=PINK)
    return img


if __name__ == "__main__":
    filename = fd.load_filename()

    img = load_img(filename)
    display(img)

    #width, height = get_width_and_height(img)

    crop_inst = CropShape(img, 1)
    mask, crop, boundary, crop_points = crop_inst.begin_crop()

    masked_im = mask_img(img, mask)
    masked_and_cropped = crop_img(masked_im, crop)
    display(masked_and_cropped, 'masked and cropped')

    img = ~img

def up_and_down(file1, file2):
    data1 = dataframes.DataStore(file1)
    data2 = dataframes.DataStore(file2)
    duty1, order1 = duty_order(data1)
    duty2, order2 = duty_order(data2)
    plotter = plotting.Plotter()
    plotter.add_plot(duty1, order1, label='up')
    plotter.add_plot(duty2, order2, label='down')
    plotter.configure_legend()
    plotter.show_figure()


def duty_order(data):
    fdata = data.frame_data
    fdata = fdata.groupby('Duty').mean()
    return fdata.index.values, fdata['mean order'].values


if __name__ == "__main__":
    from Generic import filedialogs
    file1 = filedialogs.load_filename('Select a dataframe',
                                      directory="/media/data/Data",
                                      file_filter='*.hdf5')
    file2 = filedialogs.load_filename('Select a dataframe',
                                      directory="/media/data/Data",
                                      file_filter='*.hdf5')
    up_and_down(file1, file2)
    frame_order(file1)
    # order_histogram(filename, np.arange(0, 20000, 1000))
示例#12
0
import numpy as np
import Generic.filedialogs as fd
import matplotlib.pyplot as plt
import Generic.plotting as p



if __name__ == '__main__':
    scale=3.215E-1 #microm/pixel
    fps=2.0
    filename = fd.load_filename(directory='/media/ppzmis/data/Cracks/2020_02_14',file_filter='*.txt')
    crack_width = np.loadtxt(filename)

    #Calculate crack tip trajectory
    tip_pos=np.zeros(np.shape(crack_width[:,1]))
    rad_tip=np.zeros(np.shape(tip_pos))
    for i in range(np.shape(crack_width)[0]-1):
        index = np.max(np.where(crack_width[i,:] > 1))
        tip_pos[i]=index
        rad_tip[i]=np.max(np.sum(crack_width[:,index-50:index]))



    time = (1/fps)*np.arange(0,np.size(tip_pos))
    tip_pos = scale*tip_pos
    rad_tip = scale * rad_tip/2

    np.savetxt(filename[:-4] + '_tiptraj.txt',np.c_[time,tip_pos])


示例#13
0
    %lprun -f ParticleSimulator.evolve benchmark()
    %mprun -f benchmark_memory benchmark_memory()
    '''

    #Define particles
    n_particles = 300
    particles = [Particle([0 , 0, 0], [0,0,0]) for i in range(n_particles)]
    #Define simulation boundary
    scene = Scene()
    #Data dump every dt
    dt = 1
    time_step = 0.001
    t_sim = 10


    filename_sim = load_filename(directory='/home/mike/Documents/particle_sim/init_sim/',
                                      file_filter='*.sim_setup')
    filename_scene = load_filename(directory='/home/mike/Documents/particle_sim/init_sim/', file_filter='*.scene')





    filename_op = dirname(filename_sim) + '/../sim_output/' + splitext(basename(filename_sim))[0] + '.sim_result'
    with open(filename_op, "a+") as f:
        # Create simulation
        simulator = ParticleSimulator(f,particles,time_step)
        simulator.store_particle_data(particles)
        for i in range(int(t_sim/dt)):
            simulator.evolve(dt)
            simulator.store_particle_data(particles)
示例#14
0
                                    self.param_dict['window'][0],
                                    self.param_dict['constant'][0],
                                    self.param_dict['invert'][0])

        watershed_img = watershed(
            self.im0.copy(),
            watershed_threshold=self.param_dict['watershed_thresh'][0],
            block_size=self.param_dict['window'][0],
            constant=self.param_dict['constant'][0],
            mode=self.param_dict['invert'][0])
        self._display_img(thresh, watershed_img)


if __name__ == "__main__":
    """
    Relative import will break when running this file as top-level

    Run functions from images as images.function_name
    """
    from Generic import video, images, filedialogs
    file = filedialogs.load_filename('Load a video')
    vid = video.ReadVideo(file)
    # frame = images.bgr_2_grayscale(frame)
    images.CircleGui(vid)
    # images.ThresholdGui(vid)
    # images.AdaptiveThresholdGui(vid)
    #images.ContoursGui(vid,thickness=-1)
    #images.InrangeGui(vid)
    #images.DistanceTransformGui(vid)
    # images.WatershedGui(vid)
    # images.RotatedBoxGui(vid)
import matplotlib.pyplot as plt
import numpy as np

from Generic import filedialogs
from ParticleTracking import dataframes

# %%
file = filedialogs.load_filename(file_filter='*.hdf5')

data = dataframes.DataStore(file)

data.df['order_mag'] = np.abs(data.df.order_i + data.df.order_r)

bins = [400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000]
orders = []
for i in range(len(bins) - 1):
    orders.append(
        data.df.loc[(data.df.Duty >= bins[i]) * (data.df.Duty <= bins[i + 1]),
                    'order_mag'].values)

fig, ax = plt.subplots()
for i, order in enumerate(orders):
    freq, hist_bins = np.histogram(order,
                                   bins=np.arange(0, 1.01, 0.01),
                                   density=True)
    ax.plot(hist_bins[:-1],
            freq,
            label=str(bins[i]) + ' to ' + str(bins[i + 1]))
    ax.legend()
    ax.set_title(file)
    ax.set_xlabel('Order')
示例#16
0
 def choose_port(self, os='linux'):
     if os == 'linux':
         self.port.port = fd.load_filename('Choose a comport',
                                           directory='/dev/')
示例#17
0
 def load_lut(self, filename=None):
     if filename is None:
         load_filename(directory=self.cam_config_dir, file_filter='*.lut')
     self._upload_cam_commands(self.lut_script)
示例#18
0
        order_edge = df.loc[d, ['order_abs', 'on_edge']]
        orders = order_edge.reset_index().set_index('on_edge').loc[
            False, 'order_abs'].values
        print(orders)
        freq, bins = np.histogram(orders, bins=100, density=True)
        ax.plot(bins[:-1], freq, label=d)
    ax.legend(title='Duty Cycle')
    ax.set_xlabel('Order')
    ax.set_ylabel('Frequency')
    ax.set_title(file)
    plt.show()


if __name__ == "__main__":
    import matplotlib as mpl
    import os

    sns.set_context('notebook')
    file = filedialogs.load_filename('Load a dataframe', '/media/data/data',
                                     '*.hdf5')
    mpl.rcParams["savefig.directory"] = os.path.split(file)[0]
    data = dataframes.DataStore(file)
    # duty_curve(data.df)

    df_up, df_down = split_df(data.df)

    # order_duty(df_up, df_down)

    duties = list(range(400, 1050, 50))
    order_histograms(df_down, duties)
示例#19
0
from ParticleTracking.tracking import james_nitrile as jn
from Generic import video, filedialogs
import matplotlib.pyplot as plt
import numpy as np

file = filedialogs.load_filename(directory="/media/data/Data")
vid = video.ReadVideo(file)
frames = vid.num_frames
freqs = jn.read_audio_file(file, frames)
d = np.round((freqs - 1000) / 15)
fig, ax = plt.subplots()
frames = list(range(frames))
ax.plot(frames, d)
ax.set_xlabel('frame')
ax.set_ylabel('Duty Cycle / 1000')
ax2 = ax.twinx()
ax2.plot(frames, d)
ax2.set_ylabel('Frequency (Hz)')
plt.show()
示例#20
0
from ParticleTracking import dataframes
from Generic import plotting
import matplotlib.pyplot as plt
import numpy as np

def histogram(file, duty):
    data = dataframes.DataStore(file)
    print(data.frame_data.head())
    df = data.frame_data.merge(data.df.drop('frame', 1).reset_index()).set_index('Duty')

    p = plotting.Plotter()
    for d in duty:
        orders = df.loc[d, 'real order']
        n, bins = np.histogram(orders, bins=100, density=True)
        p.add_plot(bins[:-1]+(bins[1]-bins[0])/2, n*(bins[1]-bins[0]), label=d)
    p.configure_legend()
    p.configure_xaxis(xlabel='Order Parameter')
    p.configure_yaxis(ylabel='Relative Frequency')



if __name__ == "__main__":
    from Generic import filedialogs
    file = filedialogs.load_filename()
    histogram(file, [600, 620, 640, 660, 680, 700])
    # histogram(file, [500, 600, 700, 800, 900])
示例#21
0
from Generic.fitting import Fit
from Generic.filedialogs import load_filename
import numpy as np

if __name__ == '__main__':

    filename = load_filename(directory='/media/ppzmis/SAMSUNG/crackbranching/CrackHoppingVids', file_filter='*.txt')
    time = np.loadtxt(filename, usecols=0)
    width = np.loadtxt(filename, usecols=1)

    shift_time = 133
    shift_width = 40
    time=time-shift_time
    width = width - shift_width
    indices = width > 0
    indices2 = time > 0
    indices = indices * indices2
    time = time[indices]
    width = width[indices]
    print(time)
    print(width)

    #f1 = Fit('linear', x=np.log(time), y=np.log(width))
    f1 = Fit('flipped_exponential', x=time, y=width)
    f2 = Fit('double_flipped_exponential', x=time, y=width)

    #logic1 = time > 200
    logic2 = time > 200

    #f1.plot_data()