Beispiel #1
0
def read_all_hd(
    template,
    lu: list,
    ) -> list:

    #   Initialisations
    hd = []

    #   Loop through all units
    for i in range(0, len(lu)):

        #   Create the file path of the results file
        fp_r_f = create_fp_file(template, "Hausdorff Distance_" + lu[i] + "_2", "r")

        #   Store the results from the file
        hd.append(linecache.getline(fp_r_f, 1))

    #   Clean the list
    hd = [i.rstrip() for i in hd]

    #   Cast the list items to floats and check for any failed results
    (hd, hd_f) = utility.list_to_float(hd)

    #   Output a warning if any models failed to deliver results
    if hd_f != 0:
        print("Warning: {} models failed to deliver results!".format(hd_f))

    hd = list(map(abs, hd))

    return hd
Beispiel #2
0
def open_v(
    template,
    l: str,
    ):
    """Open a variable saved to a file

    Parameters
    ----------
    fp : str
        The file path

    Returns
    -------
    
        The saved variable
    """

    fp = file_paths.create_fp_file(template, l, "v")

    #   Open the file to be read from
    f = open(fp, "rb")

    #   Store the variable
    v = pickle.load(f)

    #   Close the file
    f.close()

    return v
Beispiel #3
0
def save_v(
    template,
    v,
    l: str,
    ) -> None:
    """Save a variable as a file

    Parameters
    ----------
    v : 
        The variable to be saved
    l : str
        The file path
    """

    fp = file_paths.create_fp_file(template, l, "v")

    #   Open the file to be written to
    f = open(fp, 'wb')

    #   Save the variable
    pickle.dump(v, f)

    #   Close the file
    f.close()

    return
Beispiel #4
0
def read_val(
    template,
    l: str,
    ) -> float:
    """Read a specific value from a results file

    Parameters
    ----------
    template 
        The unit template parameters
    l : str
        The label for the results file
        Either a template or unit identifier

    Returns
    -------
    float
        The found value
    """

    #   Create the file path of the results file
    fp_r_f = create_fp_file(template, l, "r")

    #   Read the value as a float if possible
    try:
        val = float(linecache.getline(fp_r_f, template.n_steps + 1))
    except:
        val = None

    return val
def save_numpy_array_to_csv(
    template,
    l: str,
    data: numpy.array,
) -> None:
    """Write the results to .csv files

    Parameters
    ----------
    template 
        The unit template parameters
    l : str
        The label of the data
    data : numpy.array
        The results to be stored
    """

    #   Create the file path of the results file
    fp_r_f = create_fp_file(template, l, "r")

    #   Write the data to the results file
    numpy.savetxt(fp_r_f, data, delimiter=",")

    print("{}.csv saved".format(l))

    return
Beispiel #6
0
def save_2d_list_to_csv(
    template,
    l: str,
    data: numpy.array,
    ) -> None:
    """Write the results to .csv files

    Parameters
    ----------
    template 
        The unit template parameters
    l : str
        The label of the data
    data : numpy.array
        The results to be stored
    """

    #   Create the file path of the results file
    fp_r_f = create_fp_file(template, l, "r")

    #   Write the data to the results file
    with open(fp_r_f, 'w') as f:
        wr = csv.writer(f)
        wr.writerows(data)

    print("{}.csv saved".format(l))

    return
Beispiel #7
0
def save_plot(
    template,
    t: str,
    tm: str,
    ) -> None:
    """Save a figure

    Parameters
    ----------
    template
        The unit template parameters
    t : str
        The title of the graph
    tm : str
        The timestamp of the current simulation
    """    

    #   Create the file path of the figure
    fp_p = file_paths.create_fp_file(template, t + tm, "g")

    plot.tight_layout()

    #   Save the figure
    plot.savefig(fp_p, dpi = 300)

    #   Close the figure
    plot.close()

    return
    def create_fp_list(
        self,
        ext: str,
    ) -> list:
        """Create a list of unit file paths

        Parameters
        ----------
        ext : str
            The extension to add to the file path

        Returns
        -------
        list
            The list of file paths
        """

        fp_list = []

        for i in range(1, 4):

            fp_list.append(
                create_fp_file(self.template, "_job_{}.{}".format(i, ext), "u",
                               self))

        return fp_list
def internal_energy(
    template,
    l: str,
) -> None:
    """Calculate the internal energy for a unit

    Parameters
    ----------
    template 
        The unit template parameters
    l : str
        The label for the results file
        Either a template or unit identifier
    """

    #   Initialisations
    label = []
    label.append("Comp 11 of Total Strain")
    label.append("Comp 22 of Total Strain")
    label.append("Total Strain Energy Density")

    label_i_e = []
    label_i_e.append("Internal Energy X")
    label_i_e.append("Internal Energy Y")
    label_i_e.append("Internal Energy")

    s = numpy.zeros((len(label), template.n_steps + 1, template.n_n))

    #   Loop through all the variable labels
    for i in range(0, len(label)):

        #   Create the file path of the results file
        fp_r_f = create_fp_file(template, label[i] + "_" + l, "r")

        #   Store the results from the file
        s[i] = numpy.genfromtxt(fp_r_f, delimiter=",")

    #   Loop through all the internal energy labels
    for i in range(0, len(label_i_e)):

        #   Initialise the internal energy array
        i_e = numpy.zeros(len(s[i]))

        #   Loop through every step in the unit
        for j in range(0, len(s[i])):

            #   Loop through every external node
            for k in range(0, len(s[i, i])):

                #   Calculate the internal energy for the current step
                i_e[j] += s[i, j, k]

        #   Save the internal energy to a .csv file
        save_numpy_array_to_csv(template, label_i_e[i] + "_" + l, i_e)

    return
Beispiel #10
0
def read_all(
    template,
    lu: list,
    l: str,
    ) -> list:
    """Read all result values from a list of units and plot them

    Parameters
    ----------
    l : str
        The result label
    lu : list
        The list of units
    template : template
        The unit template parameters

    Returns
    -------
    list
        The list of values
    """    

    #   Initialisations
    v = []

    #   Loop through all units
    for i in range(0, len(lu)):

        #   Initialisations
        v.append([])

        #   Create the file path of the results file
        fp_r_f = create_fp_file(template, l + "_" + lu[i] + "_2", "r")

        #   Store the results from the file
        v[i] = linecache.getline(fp_r_f, template.n_steps + 1)

    #   Clean the list
    v = [i.rstrip() for i in v]

    #   Cast the list items to floats and check for any failed results
    (v, v_f) = utility.list_to_float(v)

    #   Output a warning if any models failed to deliver results
    if v_f != 0:
        print("Warning: {} models failed to deliver results!".format(v_f))

    v = list(map(abs, v))

    return v
Beispiel #11
0
def disp(
    template,
    l: str,
) -> list:
    """Read the displacement values for a unit

    Parameters
    ----------
    template : template
        The unit template parameters
    l : str
        The label for the results file
        Either a template or unit identifier

    Returns
    -------
    list
        The list of displacement values
    """

    #   Initialisations
    label = []
    label.append("Displacement X")
    label.append("Displacement Y")

    d = numpy.zeros((len(label), template.n_steps + 1, template.n_n))

    #   Loop through the list of labels
    for i in range(0, len(label)):

        #   Create the file path of the results file
        fp_r_f = create_fp_file(template, label[i] + "_" + l, "r")

        #   Store the results from the file
        d[i] = numpy.genfromtxt(fp_r_f, delimiter=",")

    #   Decrement the node IDs of the external nodes by 1 to be used as array indices
    n_external_i = [i - 1 for i in template.n_external]

    #   Store only the external node values
    d_ex = d[:, :, n_external_i]

    #   Store only the final values in the simulation
    d_ex = d_ex[:, template.n_steps]

    return d_ex
Beispiel #12
0
def read_all_fit(
    template,
    lu: list,
    ) -> list:

    if template.case == 1:

        #   Initialisations
        r = []
        w = []

        #   Loop through all units
        for i in range(0, len(lu)):

            #   Create the file path of the results file
            fp_r_f = create_fp_file(template, "Case 1 Fitness Measures_" + lu[i] + "_2", "r")

            #   Store the results from the file
            r.append(linecache.getline(fp_r_f, 1))
            w.append(linecache.getline(fp_r_f, 2))

        #   Clean the list
        r = [i.rstrip() for i in r]
        w = [i.rstrip() for i in w]

        #   Cast the list items to floats and check for any failed results
        (r, r_f) = utility.list_to_float(r)
        (w, w_f) = utility.list_to_float(w)  

        #   Output a warning if any models failed to deliver results
        if r_f != 0:
            print("Warning: {} models failed to deliver results!".format(r_f))
        if w_f != 0:
            print("Warning: {} models failed to deliver results!".format(w_f))

        r = list(map(abs, r))
        w = list(map(abs, w))

        fit_m = [r, w]

    return fit_m
Beispiel #13
0
def run_units(
    template,
    l_u: list,
    meth: str,
) -> [list, str, str]:
    """Run a list of units

    Parameters
    ----------
    template : template
        The unit template parameters
    l_u : list
        The list of unit parameters
    meth : str
        The unit generation method
        l:  L-Systems
        c:  CPPNs
        r:  Random

    Returns
    -------
    [str, str]
        The file paths of the list of units generated and ranked
    """

    #   The time the unit generation starts as a string label
    t = time.strftime("_%Y-%m-%d--%H-%M-%S", time.gmtime())

    #   Create the file paths of the log files of units created during the simulation
    #   0:  all
    #   1:  successful
    #   2:  failed
    #   3:  empty
    #   4:  full
    #   5:  ranked
    fp_lu = [
        create_fp_file(template, t, "l"),
        create_fp_file(template, t + "_success", "l"),
        create_fp_file(template, t + "_failed", "l"),
        create_fp_file(template, t + "_empty", "l"),
        create_fp_file(template, t + "_full", "l"),
        create_fp_file(template, t + "_ranked", "l")
    ]

    #   Run the empty and full units
    empty_id, full_id = empty_full(template, fp_lu)

    #   Loop through the list of units generated
    for i in l_u:

        #   Open the template file
        modify.open_model(template.fp_t_mud)

        #   Generate the grid with elements removed, search for any free element clusters, and update the grid and list
        grid_rem, rem = gen_grid_rem_free(template, i[0])

        #   Check if all internal elements were removed from the current unit
        if len(rem) == len(template.e_internal):

            #   Add an exception for an empty unit
            add_exc(template, fp_lu, rem, grid_rem, empty_id, meth, i[1])

        elif len(rem) == 0:

            #   Add an exception for an empty unit
            add_exc(template, fp_lu, rem, grid_rem, full_id, meth, i[1])

        else:

            #   Check if the unit generation method is set to L-Systems
            if meth == "l":

                #   Remove the elements, save and run the model and obtain the desired results
                rem_el_run_results(template, rem, grid_rem, fp_lu, ls=i[1])

            #   Check if the unit generation method is set to CPPNs
            elif meth == "c":

                #   Remove the elements, save and run the model and obtain the desired results
                rem_el_run_results(template, rem, grid_rem, fp_lu, cp=i[1])

            #   Check if the unit generation method is set to random
            else:

                #   Remove the elements, save and run the model and obtain the desired results
                rem_el_run_results(template, rem, grid_rem, fp_lu)

    return fp_lu, empty_id, full_id
Beispiel #14
0
def constraint_energy(
    template,
    l: str,
) -> None:
    """Calculate the constraint energy for a unit

    Parameters
    ----------
    template : template
        The unit template parameters
    l : str
        The label for the results file
        Either a template or unit identifier
    """

    #   Initialisations
    label = []
    label.append("Displacement X")
    label.append("Displacement Y")
    label.append("Displacement")
    label.append("Reaction Force X")
    label.append("Reaction Force Y")
    label.append("Reaction Force")

    label_c_e = []
    label_c_e.append("Constraint Energy X")
    label_c_e.append("Constraint Energy Y")
    label_c_e.append("Constraint Energy")

    v = numpy.zeros((len(label), template.n_steps + 1, template.n_n))

    #   Loop through all the variable labels
    for i in range(0, len(label)):

        #   Create the file path of the results file
        fp_r_f = create_fp_file(template, label[i] + "_" + l, "r")

        #   Store the results from the file
        v[i] = numpy.genfromtxt(fp_r_f, delimiter=",")

    #   Decrement the node IDs of the external nodes by 1 to be used as array indices
    n_external_i = [i - 1 for i in template.n_external]

    #   Store only the external node values
    v_ex = v[:, :, n_external_i]

    #   Loop through every constraint energy label
    for i in range(0, len(label_c_e)):

        #   Initialise the constraint energy array
        c_e = numpy.zeros(len(v_ex[i]))

        #   Loop through every step in the unit
        for j in range(0, len(v_ex[i])):

            #   Loop through every external node
            for k in range(0, len(v_ex[i, i])):

                #   Calculate the constraint energy for the current step
                c_e[j] += v_ex[i, j, k] * v_ex[i + len(label_c_e), j, k] / 1000

        #   Save the constraint energy to a .csv file
        save_numpy_array_to_csv(template, label_c_e[i] + "_" + l, c_e)

    return
Beispiel #15
0
class template:
    """Unit template parameters
    """
    def __init__(
        self,
        case: int,
        x_e: int,
        y_e: int,
        e_s: float,
        b: int,
        ogd_mat: ogd_mat,
        n_steps: int,
        tab_nam: str,
        d_mag: float,
        p_mag: float,
        run_success: bool = False,
        c_e: list = [0, 0, 0],
        i_e: list = [0, 0, 0],
    ) -> None:
        """[summary]

        Parameters
        ----------
        case : int
            The unit template case identifier
        x_e : int
            The number of elements in the x-direction
        y_e : int
            The number of elements in the y-direction
        e_s : float
            The element size in mm
        b : int
            The number of elements in the boundary of the unit
        ogd_mat : ogd_mat
            The Ogden material model
        n_steps : int
            The number of steps in the second of the simulation
        tab_nam : str
            The name of the table containing the function of the load to be applied
        d_mag : float
            The magnitude of the applied displacement in mm
        p_mag : float
            The magnitude of the applied internal pressure in MPa
        run_success : bool, optional
            The success of the unit template's run, by default False
        c_e : list, optional
            The constraint energy of the unit template, by default [0, 0, 0]
        i_e : list, optional
            The internal energy of the unit template, by default [0, 0, 0]
        """

        self.case = case

        if x_e % 2 == 0:
            self.x_e = x_e + 1
        else:
            self.x_e = x_e

        if y_e % 2 == 0:
            self.y_e = y_e + 1
        else:
            self.y_e = y_e

        self.e_s = e_s
        self.b = b
        self.ogd_mat = ogd_mat
        self.n_steps = n_steps
        self.tab_nam = tab_nam
        self.d_mag = d_mag
        self.p_mag = p_mag
        self.run_success = run_success
        self.c_e = c_e
        self.i_e = i_e

        self.x_s = self.e_s * self.x_e
        self.y_s = self.e_s * self.x_e

        #   The number of nodes in the x-direction
        self.x_n = self.x_e + 1
        #   The number of nodes in the y-direction
        self.y_n = self.y_e + 1
        #   The total number of elements
        self.n_e = self.x_e * self.y_e
        #   The total number of nodes
        self.n_n = self.x_n * self.y_n
        #   The list of internal elements
        self.e_internal = inspect.find_e_internal(self.x_e, self.y_e, self.b)
        #   The list of external nodes
        self.n_external = inspect.find_n_external(self.x_n, self.y_n)

        #   The total number of elements as a string label
        self.n_e_l = utility.list_to_str([self.x_e, self.y_e], "x")
        #   The size of the grid as a string label
        self.s_l = utility.list_to_str([self.x_s, self.y_s], "x")

        #   The template ID
        self.t_id = str(
            self.case) + "_" + self.n_e_l + "_" + self.s_l + "_" + str(self.b)

        #   The representative grid of ones
        self.grid = rep_grid.create_grid(self.x_e, self.y_e, 1)

        #   The file path of the template file
        self.fp_t_mud = create_fp_file(self, ".mud", "t")
        #   The file path of the template file log
        self.fp_t_log = create_fp_file(self, "_job_1.log", "t")
        #   The file path of the unit t16 file
        self.fp_t_t16 = create_fp_file(self, "_job_1.t16", "t")
        #   The file path of the template file log
        self.fp_t_l = create_fp_file(self, ".log", "t")
Beispiel #16
0
    def __init__(
        self,
        template: template,
        rem: list,
        grid: list,
        ls=None,
        cp=None,
        run_success: bool = False,
        c_e: list = [0, 0, 0],
        i_e: list = [0, 0, 0],
        d: list = [],
    ) -> None:
        """The unit parameters

        Parameters
        ----------
        template : template
            The unit template parameters
        rem : list
            The list of elements removed from the unit
        grid : list
            The representative grid with the elements removed
        ls : lsystem, optional
            The L-System, by default None
        cp : cppn_i, optional
            The CPPN model, by default None
        run_success : bool, optional
            The success of the unit's run, by default False
        c_e : list, optional
            The constraint energy of the unit template, by default [0, 0, 0]
        i_e : list, optional
            The internal energy of the unit template, by default [0, 0, 0]
        d : list, optional
            [description], by default []
        """

        self.template = template
        self.rem = rem
        self.grid = grid
        self.ls = ls
        self.cp = cp
        self.run_success = run_success
        self.c_e = c_e
        self.i_e = i_e
        self.d = d

        #   The list of elements removed from the unit as a string
        self.rem_l = utility.list_to_str(rem, "_")

        #   Generate the unique unit ID according to the method of unit generation
        if self.ls != None:

            self.u_id = str(len(self.rem)) + "_" + utility.gen_hash(
                utility.list_to_str(self.ls.gramm, "_"))

        elif self.cp != None:

            self.u_id = str(len(self.rem)) + "_" + str(
                self.cp.mod_id) + "_" + str(self.cp.cppn.seed) + "_" + str(
                    self.cp.cppn.scale) + "_" + str(
                        self.cp.cppn.hl_n) + "_" + str(
                            self.cp.cppn.hl_s) + "_" + str(self.cp.cppn.thresh)

        else:

            self.u_id = str(len(self.rem)) + "_" + utility.gen_hash(self.rem_l)

        #   The representative grid with the elements removed as a string label
        self.grid_l = self.format_grid()

        #   The file path of the unit file
        self.fp_u_mud = create_fp_file(self.template, ".mud", "u", self)
        #   The file path of the unit log file
        self.fp_u_log = self.create_fp_list("log")
        #   The file path of the unit t16 file
        self.fp_u_t16 = self.create_fp_list("t16")
        #   The file path of the unit file log
        self.fp_u_l = create_fp_file(self.template, ".log", "u", self)
Beispiel #17
0
def main():

    #   Reload the modules
    importlib.reload(classes)
    importlib.reload(file_paths)
    importlib.reload(plotting)
    importlib.reload(utility)
    importlib.reload(cppns)
    importlib.reload(gen_alg)
    importlib.reload(lsystems)
    importlib.reload(analyse)
    importlib.reload(obtain)
    importlib.reload(create)
    importlib.reload(inspect)
    importlib.reload(modify)
    importlib.reload(rep_grid)

    #   Initialisations
    #   The template case identifier
    case = 1
    #   The number of elements in each axis direction
    x_e = 15
    y_e = 15
    #   The length of each side in mm
    e_s = 10
    #   The thickness of the unit boundary
    b = 3
    #   The number of increments per second to analyse
    n_steps = 5
    #   The text name of the table used for the applied displacement and load
    table_name = "ramp_input"
    #   The magnitude of the applied displacement in mm
    d_mag = y_e*e_s/2
    #   The magnitude of the applied internal pressure in MPa
    p_mag = 0.025

    #   The unit generation method
    g_meth = "r"
    #   The analysis method
    a_meth = "g"

    #   Genetic algorithm parameters
    gen = 15
    prob = [0.5, 0.1, 0.5]
    point = [1, 2, 2]

    #   Prepare the unit parameters
    temp = classes.template(case, x_e, y_e, e_s, b, classes.mold_star_15, n_steps, table_name, d_mag, p_mag)

    # for i in range(1, 10):

    #     l = lsystems.lsystem(lsystems.e_vocabulary, [["F", "FF++f"], ["f", "--FFF"]], lsystems.a_rot_hor, i)

    #     c = lsystems.interpret_word_raw(l.word)

    #     grid = utility.coord_to_grid(c)

    #     plotting.grid_plot(temp, "_layout", grid, "ls_" + str(i))

    # for xy in range (5, 31, 5):

    #     c = cppns.cppn(29, 29, 2, 11, 23, 42, xy, xy)

    #     c_i = cppns.cppn_i(c, 28)

    #     plotting.grid_plot(temp, "_layout", c_i.grid, "cppn_" + str(xy))

    t = "_2020-10-28--16-00-12"

    # 2020-10-29--14-18-46 
    # 2020-11-14--07-51-17
    # 2020-10-28--16-00-12
    # 2020-11-19--12-47-03

    #   Generate the grid with all elements removed
    grid_rem_e, rem_e = create.gen_grid_rem_free(temp, temp.e_internal)

    #   Generate the unit ID of the empty unit
    empty_id = str(len(rem_e)) + "_" + utility.gen_hash(utility.list_to_str(rem_e, "_"))

    #   Generate the grid with all elements removed
    grid_rem_f, rem_f = create.gen_grid_rem_free(temp, [])

    #   Generate the unit ID of the full unit
    full_id = str(len(rem_f)) + "_" + utility.gen_hash(utility.list_to_str(rem_f, "_"))

    fp_lu = [create_fp_file(temp, t, "l"), create_fp_file(temp, t + "_success", "l"), create_fp_file(temp, t + "_failed", "l"), create_fp_file(temp, t + "_empty", "l"), create_fp_file(temp, t + "_full", "l"), create_fp_file(temp, t + "_ranked", "l")]

    data = analyse.rank_u(temp, g_meth, empty_id, full_id, fp_lu)

    data["Constraint Energy"] = data["Constraint Energy"]*1000

    data = data[(data["Constraint Energy"] >= 0) & (data["Constraint Energy"] < 0.1)]

    plotting.hist(temp, t, data, "Constraint Energy")
    plotting.hist(temp, t, data, "Internal Energy")

    # data_x = ["Number of Hidden Layers", "Size of the Initial Hidden Layer"]

    data_y = ["Constraint Energy", "Internal Energy"]

    # plotting.scat_all(temp, t, data, ["Size of the Initial Hidden Layer"], data_y)
    
    # plotting.boxp_all(temp, t, data, ["Number of Hidden Layers"], data_y)

    plotting.lreg_all(temp, t, data, ["Number of Elements Removed"], data_y)

    return