Esempio n. 1
0
 def analyze_bang_bang_response(bang_bang_response):
     t_data = _array([t for t,PV in bang_bang_response])
     PV_data = _array([PV for t,PV in bang_bang_response])
     amp = (PV_data.max() - PV_data.min()) / 2
     freq = Controller._get_frequency(x_data=t_data, y_data=PV_data)
     period = 1./freq
     return (amp, period)
Esempio n. 2
0
def xyz2input(filename):
    """
    Reads a .xyz and return an ABINIT input
    as a python dictionary
    """

    abiinput = InputVariables()
    atomdict = _atom_symbol()
    rf = open(filename, 'r')

    natom = int(rf.readline())
    typat = []
    znucl = []
    xcart = []
    xangst = []

    ntypat = 0
    rf.readline()
    data = rf.readlines()
    for i in range(natom):
        atom = data[i].split()
        atomnumber = atomdict[atom[0]]
        if not atomnumber in znucl:
            ntypat += 1
            znucl.append(atomnumber)
        typat.append(znucl.index(atomnumber) + 1)
        xangst = xangst + [float(atom[1]), float(atom[2]), float(atom[3])]

    abiinput.variables['natom'] = _array([natom])
    abiinput.variables['znucl'] = _array(znucl)
    abiinput.variables['ntypat'] = _array([ntypat])
    abiinput.variables['typat'] = _array(typat)
    abiinput.variables['xcart'] = _angstrom_bohr * _array(xangst)

    return abiinput
Esempio n. 3
0
 def analyze_bang_bang_response(bang_bang_response):
     t_data = _array([t for t,PV in bang_bang_response])
     PV_data = _array([PV for t,PV in bang_bang_response])
     amp = (PV_data.max() - PV_data.min()) / 2
     freq = Controller._get_frequency(x_data=t_data, y_data=PV_data)
     period = 1./freq
     return (amp, period)
def trapizoidal(f, limits, ns):
    """This function calculates the area under a given curve between the given
    list of limit points using Trapezoidal method

    Parameters
    ----------
    f : function
        function whose area is to be calculated
    limits : tuple
        a tuple of limit points
    ns : iterable
        list of number of sub intervals

    Returns
    -------
    Intergral : List
        List of area calculated using corresponding values of ns
    hs : List
        List of h for corresponding values of ns

    """
    a, b = limits
    hs = [(b - a) / k for k in ns]

    Intergral = []

    for i in range(len(ns)):
        coeffs = _array([2.0] * (ns[i] + 1))
        coeffs[0] = coeffs[-1] = 1.0
        points = _array([f(a + k * hs[i]) for k in range(ns[i] + 1)])
        area = sum(coeffs * points) * hs[i] * 0.5
        Intergral.append(area)

    return Intergral, hs
Esempio n. 5
0
def plot_simple(variables, varname):
    from matplotlib.pylab import subplots
    from numpy import arange, mean, apply_along_axis, linalg
    from math import sqrt

    fig, ax = subplots(nrows=1, ncols=1)
    fig.set_size_inches(15, 4)

    ndtset = variables['ndtset'][0]
    lens = _array([len(variables[varname + str(x + 1)]) for x in range(ndtset)])

    x = arange(ndtset) + 1

    if max(lens) == min(lens):
        if lens[0] == 1:
            y = _array([variables['etotal' + str(x + 1)][0] for x in range(ndtset)])
        elif lens[0] % 3 == 0:
            y = _array([mean(apply_along_axis(linalg.norm, 1, variables['fcart' + str(x + 1)].reshape((-1, 3))))
                        for x in range(ndtset)])
        else:
            y = _array([sqrt(sum(variables['fcart' + str(x + 1)] ** 2)) for x in range(ndtset)])
    ax.plot(x, y, 'ro')
    ax.plot(x, y, 'b-')
    ax.set_xlabel('Dataset')
    ax.set_ylabel(varname)
    ax.set_xlim(1, ndtset + 1)
    if ndtset < 30:
        ax.set_xticks(arange(ndtset + 1))
        ax.grid(which='major', axis='both')
Esempio n. 6
0
 def checkWall1(self):
     p = _mapTools.mousePos()
     self.initChoices = ([0, 1], [0, -1], [1, 0], [-1, 0])
     if self.grid[p[1]][p[0]] == 0 and self.movingWall == None:
         for m in self.initChoices:
             newp = _array(p) + _array(m)
             if self.grid[newp[1]][newp[0]] == 0:
                 self.movingWall = [p]
Esempio n. 7
0
def create_tetrahedron_vbo(edge=1.0):
    """
    Creates a VBO tetrahedron for shaders.

    :param edge: Edge length
    :type edge: float, int
    :return: VBO object
    :rtype: VBObject
    """
    def ex(element):
        """
        Export element to list.

        :param element: Element
        :return: List
        :rtype: list
        """
        return element.export_to_list()

    # Create points
    a = Point3(-0.5, -0.288675, -0.288675) * edge
    b = Point3(0.5, -0.288675, -0.288675) * edge
    # noinspection PyArgumentEqualDefault
    c = Point3(0.0, 0.577350, -0.288675) * edge
    # noinspection PyArgumentEqualDefault
    d = Point3(0.0, 0.0, 0.57735) * edge

    # Create normals
    n1 = ex(_normal_3_points(a, b, d))
    n2 = ex(_normal_3_points(b, c, d))
    n3 = ex(_normal_3_points(c, a, d))
    n4 = ex(_normal_3_points(c, b, a))

    # Create triangles
    vertex_array = [
        ex(a),
        ex(b),
        ex(d),
        ex(b),
        ex(c),
        ex(d),
        ex(c),
        ex(a),
        ex(d),
        ex(a),
        ex(b),
        ex(c)
    ]
    normal_array = [n1, n1, n1, n2, n2, n2, n3, n3, n3, n4, n4, n4]

    # Return VBO
    return VBObject(_vbo.VBO(_array(vertex_array, 'f')),
                    _vbo.VBO(_array(normal_array, 'f')), len(vertex_array))
Esempio n. 8
0
 def move(self,pos):
     if tuple(self.pos)==self.initPos:
         if pos in self.moveChoices():
             self.pos=_array(pos)
             self.grid[self.pos[1]][self.pos[0]]=4
             if self.cheatmode == False:
                 self.controller.turn()[1].moveReady=False
     else:
         if pos in self.moveChoices():
             self.grid[self.pos[1]][self.pos[0]]=0
             self.pos=_array(pos)
             self.grid[self.pos[1]][self.pos[0]]=4
             if self.cheatmode == False:
                 self.controller.turn()[1].moveReady=False
Esempio n. 9
0
 def move(self, pos, roll):
     if pos in self.moveChoices(roll):
         self.grid[self.pos[1]][self.pos[0]] = 0
         self.pos = _array(pos)
         self.grid[self.pos[1]][self.pos[0]] = 3
         if self.cheatmode == False:
             self.controller.turn()[1].moveReady = False
Esempio n. 10
0
def s(data, filename='tmp.dat'):
    '''
    saves arrays into an ASCII file easily read in gnuplot
    >>> s(data, filename='tmp.dat')  # overwrites/creates tmp.dat
    '''
    data = _transpose(data)
    _savetxt(filename, _array(data), delimiter=', ')
Esempio n. 11
0
    def set_complex_positions(self,positions):

        tmp_positions = self.modeller.getPositions()
        tmp_positions = _array(tmp_positions._value)*tmp_positions.unit
        tmp_positions[self.complex_atom_indices]=positions
        self.modeller.positions  = tmp_positions
        self.positions           = self.modeller.getPositions()
Esempio n. 12
0
 def pathFinder(posLayer, m):
     newPosLayer=[]
     initChoices = ([0,1],[0,-1],[1,0],[-1,0])
     for p in posLayer:
         for i in initChoices:
             newp = _array(p)+_array(i)
             if self.grid[newp[1]][newp[0]]==0:
                 newPosLayer.append(list(newp))
             elif self.grid[newp[1]][newp[0]]==3:
                 newPosLayer.append(list(newp))
                 compList.append(list(newp))
     m-=1
     newPosLayer= _mapTools.removeDuplicates(newPosLayer)
     if m==0:
         return newPosLayer
     else:
         return pathFinder(newPosLayer,m)
Esempio n. 13
0
def float_rewards(rbound,N):
    """
    Returns an array of N float rewards with absolute value <= rbound
    """
    
    signs = _array([_choice([-1,1])]*N)

    return rbound*signs*_randnum(N)
Esempio n. 14
0
 def pathFinder(posLayer, m):
     if self.play:
         newPosLayer = []
         initChoices = ([0, 1], [0, -1], [1, 0], [-1, 0])
         for p in posLayer:
             for i in initChoices:
                 newp = _array(p) + _array(i)
                 if self.grid[newp[1]][newp[0]] == 0:
                     newPosLayer.append(list(newp))
                 elif self.grid[newp[1]][newp[0]] == 5:
                     newPosLayer.append(list(newp))
                     compList.append(list(newp))
         m -= 1
         if m == 0:
             return newPosLayer
         else:
             return pathFinder(newPosLayer, m)
     else:
         return []
Esempio n. 15
0
 def __init__(self, colour, pos, fps, grid, cheatmode, controller):
     self.colour = colour
     self.pos = _array(pos)
     self.play = True
     self.finishPoints = fps
     self.cheatmode = cheatmode
     self.grid = grid
     self.controller = controller
     #Sets figure's grid position to 3
     grid[self.pos[1]][self.pos[0]] = 3
Esempio n. 16
0
 def analyze_step_response(step_response, mv_shift):
     rates = [(PVb-PVa)/(tb-ta) for ((ta,PVa),(tb,PVb))
              in zip(step_response, step_response[1:])]
     # TODO: averaging filter?
     max_rate_i = max_rate = 0
     for i,rate in enumerate(rates):
         if abs(rate) > max_rate:  # handle steps in both directions
             max_rate_i = i
             max_rate = abs(rate)
     max_rate_time,max_rate_temp = step_response[max_rate_i]  # TODO: avg i and i+1?
     time_a,PV_a = step_response[0]
     max_rate_time -= time_a
     dead_time = max_rate_time - (max_rate_temp - PV_a) / max_rate
     t_data = _array([t for t,PV in step_response[max_rate_i:]])
     PV_data = _array([PV for t,PV in step_response[max_rate_i:]])
     model = ExponentialModel(PV_data, info={'x data (s)': t_data})
     decay_time,PV0,PV8 = model.fit()
     process_gain = (PV8 - PV_a) / mv_shift
     return (process_gain, dead_time, decay_time, max_rate)
Esempio n. 17
0
 def analyze_step_response(step_response, mv_shift):
     rates = [(PVb-PVa)/(tb-ta) for ((ta,PVa),(tb,PVb))
              in zip(step_response, step_response[1:])]
     # TODO: averaging filter?
     max_rate_i = max_rate = 0
     for i,rate in enumerate(rates):
         if abs(rate) > max_rate:  # handle steps in both directions
             max_rate_i = i
             max_rate = abs(rate)
     max_rate_time,max_rate_temp = step_response[max_rate_i]  # TODO: avg i and i+1?
     time_a,PV_a = step_response[0]
     max_rate_time -= time_a
     dead_time = max_rate_time - (max_rate_temp - PV_a) / max_rate
     t_data = _array([t for t,PV in step_response[max_rate_i:]])
     PV_data = _array([PV for t,PV in step_response[max_rate_i:]])
     model = ExponentialModel(PV_data, info={'x data (s)': t_data})
     decay_time,PV0,PV8 = model.fit()
     process_gain = (PV8 - PV_a) / mv_shift
     return (process_gain, dead_time, decay_time, max_rate)
Esempio n. 18
0
def _setup_axes(*,
                input_names,
                histogram_labels=False,
                constrained_layout=True):
    """
    Setup axes
    """
    num_inputs = len(input_names)
    fig = _figure(constrained_layout=constrained_layout)
    axes = _array([[None] * num_inputs for _ in range(num_inputs)],
                  dtype=object)

    grid = _GridSpec(
        nrows=num_inputs,
        ncols=num_inputs,
        figure=fig,
    )

    common_tick_args = dict(
        top=True,
        bottom=True,
        left=True,
        right=True,
        direction='in',
    )

    for i in range(num_inputs):
        axes[i, i] = fig.add_subplot(grid[i, i])
        axes[i, i].tick_params(labelbottom=False,
                               labelleft=False,
                               labelright=histogram_labels,
                               **common_tick_args)

    for y in range(num_inputs):
        for x in range(y):
            plot_args = dict(sharex=axes[x, x])
            if y != 0:
                plot_args["sharey"] = axes[y, 0]
            axes[y, x] = fig.add_subplot(grid[y, x], **plot_args)

            if x != 0:
                axes[y, x].tick_params(labelleft=False, **common_tick_args)
            else:
                axes[y, x].set_ylabel(input_names[y])

            if y != num_inputs - 1:
                axes[y, x].tick_params(labelbottom=False, **common_tick_args)
            else:
                axes[y, x].set_xlabel(input_names[x])

    return fig, axes, grid
Esempio n. 19
0
def fmap(segments, algorithms, alt_signal=None):
    # TODO : rename extract_indicators
    """
    Generates a list composed of a list of results for each segment.

    [[result for each algorithm] for each segment]
    :param segments: An iterable of segments (e.g. an initialized SegmentGenerator)
    :param algorithms: A list of algorithms
    :param alt_signal: The signal that will be used instead of the one referenced in the segments

    :return: values, col_names A tuple: matrix (segment x algorithms) containing a value for each
     algorithm, the list of the algorithm names.
    """
    from numpy import asarray as _asarray

    seg_for = segments(alt_signal) if isinstance(
        segments, SegmentsGenerator) else segments

    values = []
    for seg in seg_for:
        segment_data = _np.array(
            [seg.get_begin_time(),
             seg.get_end_time(),
             seg.get_label()]).reshape(3, 1)
        vals_segment = []
        for alg in algorithms:
            vals_alg = _np.array(alg(seg(alt_signal)))

            if not alt_signal.is_multi():
                #                vals_alg = _np.expand_dims([vals_alg], 1)
                vals_alg = _np.array([vals_alg])
            vals_segment.append(vals_alg)

        vals_segment = _np.array(vals_segment)
        seg_data_array = _np.repeat(segment_data,
                                    alt_signal.get_nchannels(),
                                    axis=1)
        vals_segment = _np.concatenate([seg_data_array, vals_segment], axis=0)
        values.append(vals_segment)

    values = _np.array(values)

    #for compatibility
    if not alt_signal.is_multi():
        values = values[:, :, 0]

    col_names = ["begin", "end", "label"] + [x.__repr__() for x in algorithms]

    return values, _array(col_names)
def simpson38(f, limits, ns):
    """This function calculates the area under a given curve between the given
    list of limit points using Simpson 3/8 method

    Parameters
    ----------
    f : function
        function whose area is to be calculated
    limits : tuple
        a tuple of limit points
    ns : iterable
        list of number of sub intervals

    Returns
    -------
    Intergral : List
        List of area calculated using corresponding values of ns
    hs : List
        List of h for corresponding values of ns

    """
    a, b = limits
    hs = [(b - a) / k for k in ns]

    intergral = []

    for i in range(len(ns)):
        coeffs = _array([1.0] * (ns[i] + 1))
        coeffs[1:-1:3] = 3.0
        coeffs[2:-1:3] = 3.0
        coeffs[3:-1:3] = 2.0
        points = _array([f(a + k * hs[i]) for k in range(ns[i] + 1)])
        area = sum(coeffs * points) * hs[i] * 0.375
        intergral.append(area)

    return intergral, hs
Esempio n. 21
0
def rho_power(power, a, b, detuning=10, lw=10):
    """
    Transition rate of a line addressed by a detuned laser as a function of laser power
    :param power: laser power
    :param a: overall scaling parameter
    :param b: intensity scaling parameter
    :param detuning: detuning from resonance (MHz)
    :param lw: transition linewidth (MHz)
    :return: transition rate
    """
    power = _array(power)
    s = power * b
    top = a * s
    bot = 2 * (1 + s + 4 * (detuning / lw)**2)

    output = top / bot

    return output
Esempio n. 22
0
def XL_to_table(text: str = None):
    """
    Вводишь копию ячеек из XL - получаешь питоновские списки списков.
    В случае отсутствия параметров, принимает то же самое, но не в качестве аргумента, а из stdin
    """
    if text is None:
        text = _stdin
        arr = text.readline().strip()
        table = list(list() for i in range(len(arr)))
        while arr != '':
            arr = list(map(float, (arr.split('\t'))))
            for i in range(len(arr)):
                table[i].append(arr[i])
            arr = text.readline().rstrip()
            return table
    table = tuple(map(lambda x: x.split('\t'), text.split('\n')))[:-1]
    t = tuple(map(lambda x: tuple(filter(lambda y: y != '', x)), table))
    table = _array(tuple(map(lambda x: tuple(map(float, x)), t)))
    return transpose(table)
Esempio n. 23
0
def fmap(segments, algorithms, alt_signal=None):
    # TODO : rename extract_indicators
    """
    Generates a list composed of a list of results for each segment.

    [[result for each algorithm] for each segment]
    :param segments: An iterable of segments (e.g. an initialized SegmentGenerator)
    :param algorithms: A list of algorithms
    :param alt_signal: The signal that will be used instead of the one referenced in the segments

    :return: values, col_names A tuple: matrix (segment x algorithms) containing a value for each
     algorithm, the list of the algorithm names.
    """
    from numpy import asarray as _asarray
    values = _asarray([[seg.get_begin_time(), seg.get_end_time(), seg.get_label()] +
                       [alg(seg(alt_signal)) for alg in algorithms] for seg in (
        segments(alt_signal) if isinstance(segments, SegmentsGenerator) else segments
    )])
    col_names = ["begin", "end", "label"] + map(lambda x: x.__repr__(), algorithms)
    return values, _array(col_names)
Esempio n. 24
0
def fmap(segments, algorithms, alt_signal=None):
    # TODO : rename extract_indicators
    """
    Generates a list composed of a list of results for each segment.

    [[result for each algorithm] for each segment]
    :param segments: An iterable of segments (e.g. an initialized SegmentGenerator)
    :param algorithms: A list of algorithms
    :param alt_signal: The signal that will be used instead of the one referenced in the segments

    :return: values, col_names A tuple: matrix (segment x algorithms) containing a value for each
     algorithm, the list of the algorithm names.
    """
    from numpy import asarray as _asarray
    values = _asarray([[seg.get_begin_time(), seg.get_end_time(), seg.get_label()] +
                       [alg(seg(alt_signal)) for alg in algorithms] for seg in (
        segments(alt_signal) if isinstance(segments, SegmentsGenerator) else segments
    )])
    col_names = ["begin", "end", "label"] + [x.__repr__() for x in algorithms]
    return values, _array(col_names)
Esempio n. 25
0
 def estimate_pv_sensitivity(self, values=10, sleep_time=0.1,
                             max_repeats=10):
     PVs = []
     last_PV = None
     repeats = 0
     while True:
         PV = self.get_pv()
         if repeats == max_repeats:
             last_PV = None
         if PV == last_PV:
             repeats += 1
         else:
             PVs.append(PV)
             if len(PVs) > values:
                 break
             repeats = 0
             last_PV = PV
         _time.sleep(sleep_time)
     PVs = _array(PVs)
     return PVs.std()
Esempio n. 26
0
 def estimate_pv_sensitivity(self, values=10, sleep_time=0.1,
                             max_repeats=10):
     PVs = []
     last_PV = None
     repeats = 0
     while True:
         PV = self.get_pv()
         if repeats == max_repeats:
             last_PV = None
         if PV == last_PV:
             repeats += 1
         else:
             PVs.append(PV)
             if len(PVs) > values:
                 break
             repeats = 0
             last_PV = PV
         _time.sleep(sleep_time)
     PVs = _array(PVs)
     return PVs.std()
Esempio n. 27
0
 def checkWall2(self):
     newp = _mapTools.mousePos()
     correct = False
     if self.movingWall != None:
         p = self.movingWall[0]
         if newp == p:
             self.movingWall = None
         else:
             moveChoices = [
                 list(_array(p) + _array(m)) for m in self.initChoices
                 if self.grid[(_array(p) +
                               _array(m))[1]][(_array(p) +
                                               _array(m))[0]] == 0
             ]
             if newp in moveChoices:
                 self.movingWall.append(newp)
                 correct = True
             return correct
Esempio n. 28
0
    def calculate_unhashed_fps(self,
                               draw_substructures=False,
                               image_directory='./images_substructures'):
        # get the dictionary for the substructures
        idxs = []
        substr_ids = []
        counts = []
        for mol_index, mol in enumerate(self.mols):
            info = {}
            fp = _GetMorganFingerprint(mol,
                                       radius=self.max_radius,
                                       bitInfo=info)
            substructure_dictionary = {
                k: [mol_index]
                for k, v in info.iteritems() if v[0][1] in self.radii
            }
            substr_ids.append(substructure_dictionary.keys())
            idxs.append([mol_index] * len(substructure_dictionary.keys()))
            counts.append([
                len(info.values()[x]) for x in _arange(0, len(info))
                if info.values()[x][0][1] in self.radii
            ])

            # get the smiles for the substructures
            amap = {}
            substructures_smiles = {
                k: [
                    _MolToSmiles(
                        _PathToSubmol(mol,
                                      _FindAtomEnvironmentOfRadiusN(
                                          mol, v[0][1], v[0][0]),
                                      atomMap=amap))
                ]
                for k, v in info.iteritems() if v[0][1] in self.radii
            }
            self.substructures_smiles.update(substructures_smiles)

            # generate the images for the substructures if required..
            if draw_substructures:
                if not _exists(image_directory):
                    _makedirs(image_directory)
                for k, v in info.iteritems():
                    if k not in self.substructure_dictionary.keys(
                    ) and v[0][1] in self.radii:
                        image_name = "%s/Molecule_%d_substr_%d.pdf" % (
                            image_directory, mol_index, k)
                        env = _FindAtomEnvironmentOfRadiusN(
                            mol, v[0][1], v[0][0])
                        amap = {}
                        submol = _PathToSubmol(mol, env, atomMap=amap)
                        _MolToFile(mol,
                                   image_name,
                                   size=(300, 300),
                                   wedgeBonds=True,
                                   kekulize=True,
                                   highlightAtoms=amap.keys())

            self.substructure_dictionary = self._combine_dicts(
                substructure_dictionary, self.substructure_dictionary)

        idxs = _array([val for sublist in idxs for val in sublist])
        counts = _array([val for sublist in counts for val in sublist])
        substr_ids_flattened = [
            val for sublist in substr_ids for val in sublist
        ]
        substr_ids = _array(substr_ids_flattened)
        self.substructure_ids = substr_ids
        if len(self.reference_substructure_keys) == 0:
            print(
                "No input set of keys for the substructures. \nThus, the substructures present in the input molecules will be considered for the calculation of unhashed fingerprints."
            )
            columns = _array(list(set(self.substructure_dictionary.keys())))
            columns = _sort(columns)
            self.columns_unhashed = columns
            dimensionality_unhashed = len(columns)
        else:
            columns = _array(list(set(self.reference_substructure_keys)))
            columns = _sort(columns)
            self.columns_unhashed = columns
            dimensionality_unhashed = len(columns)

        fps_unhashed_binary = _zeros((len(self.mols), dimensionality_unhashed),
                                     dtype=int)
        fps_unhashed_counts = _zeros((len(self.mols), dimensionality_unhashed),
                                     dtype=int)

        # removing the indices corresponding to the substructures in the test molecules not present in the references set of substructures..
        idxs = _array([
            idxs[x] for x in _arange(0, len(substr_ids))
            if substr_ids[x] in self.columns_unhashed
        ])
        counts = _array([
            counts[x] for x in _arange(0, len(substr_ids))
            if substr_ids[x] in self.columns_unhashed
        ])
        substr_ids = _array([
            substr_ids[x] for x in _arange(0, len(substr_ids))
            if substr_ids[x] in self.columns_unhashed
        ])
        mapping = _array([(substr_ids[x] == columns).nonzero()
                          for x in _arange(0, len(substr_ids))])
        mapping = mapping.flatten()
        if len(mapping) == 0:
            print(
                "There is no intersection between the substructures \n(i)provided in the reference key set, and\n(ii) the substructures found in the input molecules."
            )
            return

        fps_unhashed_binary[idxs, mapping] = _ones(len(counts))
        fps_unhashed_counts[idxs, mapping] = counts
        self.fps_unhashed_binary = fps_unhashed_binary
        self.fps_unhashed_counts = fps_unhashed_counts
Esempio n. 29
0
    def calculate_unhashed_fps(self,draw_substructures=False,image_directory='./images_substructures'): 
        # get the dictionary for the substructures
        idxs = []
        substr_ids = []
        counts=[]
        substructure_dictionaries = []    
        for mol_index,mol in enumerate(self.mols):
            info={}
            fp = _GetMorganFingerprint(mol,radius=self.max_radius,bitInfo=info)
            substructure_dictionary = {k:mol_index for k,v in info.iteritems() if v[0][1] in self.radii}
            substructure_dictionaries.append({k:mol_index for k,v in info.iteritems() if v[0][1] in self.radii})
            substr_ids.append(substructure_dictionary.keys())
            idxs.append([mol_index]*len(substructure_dictionary.keys()))
            counts.append([ len(info.values()[x]) for x in _arange(0,len(info)) if info.values()[x][0][1] in self.radii])
            
            # get the smiles for the substructures
            amap = {}
            substructures_smiles = {k:[_MolToSmiles(_PathToSubmol(mol,_FindAtomEnvironmentOfRadiusN(mol,v[0][1],v[0][0]),atomMap=amap))] for k,v in info.iteritems() if v[0][1] in self.radii}
            self.substructures_smiles.update(substructures_smiles)
            
            # generate the images for the substructures if required..
            if draw_substructures:
                if not _exists(image_directory):
                    _makedirs(image_directory)
                for k,v in info.iteritems():
                    if k not in self.substructure_dictionary.keys() and v[0][1] in self.radii:
                        image_name="%s/Molecule_%d_substr_%d.pdf"%(image_directory,mol_index,k)
                        env=_FindAtomEnvironmentOfRadiusN(mol,v[0][1],v[0][0])
                        amap={}
                        submol=_PathToSubmol(mol,env,atomMap=amap)
                        _MolToFile(mol,image_name,size=(300,300),wedgeBonds=True,kekulize=True,highlightAtoms=amap.keys())
            
        #self.substructure_dictionary = self._combine_dicts(substructure_dictionary,self.substructure_dictionary)
        for d in substructure_dictionaries:
             for k, v in d.iteritems():
               l=self.substructure_dictionary.setdefault(k,[])
               if v not in l:
                 l.append(v)
            
        idxs = _array([val for sublist in idxs for val in sublist])
        counts = _array([val for sublist in counts for val in sublist])
        substr_ids_flattened = [val for sublist in substr_ids for val in sublist]
        substr_ids = _array(substr_ids_flattened)
        self.substructure_ids = substr_ids
        if len(self.reference_substructure_keys)==0:
            print "No input set of keys for the substructures. \nThus, the substructures present in the input molecules will be considered for the calculation of unhashed fingerprints."
            columns = _array(list(set(self.substructure_dictionary.keys())))
            columns = _sort(columns)
            self.columns_unhashed = columns
            dimensionality_unhashed = len(columns)
        else:
            columns = _array(self.reference_substructure_keys)
            columns = _sort(columns)
            self.columns_unhashed = columns
            dimensionality_unhashed = len(columns)
        
        fps_unhashed_binary = _zeros((len(self.mols),dimensionality_unhashed), dtype=int)
        fps_unhashed_counts = _zeros((len(self.mols),dimensionality_unhashed), dtype=int)

            
        mapping = _array([(substr_ids[x]==columns).nonzero() for x in _arange(0,len(substr_ids))])
        mapping = mapping.flatten()
        idxs = _array([idxs[x] for x in _arange(0,len(mapping)) if mapping[x].size != 0])
        counts = _array([counts[x] for x in _arange(0,len(mapping)) if mapping[x].size != 0])
        mapping = _array([mapping[x] for x in _arange(0,len(mapping)) if mapping[x].size != 0])
        if len(mapping) == 0:
            print "There is no intersection between the substructures \n(i)provided in the reference key set, and\n(ii) the substructures found in the input molecules."
            return
        
        fps_unhashed_binary[idxs,mapping] = _ones(len(mapping))
        fps_unhashed_counts[idxs,mapping] = counts
        self.fps_unhashed_binary = fps_unhashed_binary
        self.fps_unhashed_counts = fps_unhashed_counts
Esempio n. 30
0
 def get_complex_positions(self):
     tmp_positions = self.modeller.getPositions()
     tmp_positions = _array(tmp_positions._value)*tmp_positions.unit
     tmp_positions = tmp_positions[self.complex_atom_indices]
     return tmp_positions
Esempio n. 31
0
 def get_receptor_positions(self):
     tmp_positions = self.modeller.getPositions()
     tmp_positions = _array(tmp_positions._value)*tmp_positions.unit
     tmp_positions = tmp_positions[self.receptor_atom_indices]
     return tmp_positions
Esempio n. 32
0
class Tria6(_Element):
    nodes = 6
    dimensions = 2
    edges = _array([[0, 1, 3], [1, 2, 4], [2, 0, 5]])
Esempio n. 33
0
def create_pyramid_vbo(edge=1.0):
    """
    Creates a VBO pyramid for shaders.

    :param edge: Edge length
    :type edge: float, int
    :return: VBO Object
    :rtype: VBObject
    """
    def ex(element):
        """
        Export element to list.

        :param element: Element
        :return: List
        :rtype: list
        """
        return element.export_to_list()

    # Create points
    a = Point3(-0.5, -0.5, -0.333) * edge
    b = Point3(0.5, -0.5, -0.333) * edge
    c = Point3(0.5, 0.5, -0.333) * edge
    d = Point3(-0.5, 0.5, -0.333) * edge
    # noinspection PyArgumentEqualDefault
    e = Point3(0.0, 0.0, 0.666) * edge

    # Create normals
    n1 = ex(_normal_3_points(a, b, e))
    n2 = ex(_normal_3_points(b, c, e))
    n3 = ex(_normal_3_points(c, d, e))
    n4 = ex(_normal_3_points(d, a, e))
    n5 = ex(_normal_3_points(c, b, a))

    # Create point list
    vertex_array = [
        ex(b),
        ex(e),
        ex(a),
        ex(b),
        ex(c),
        ex(e),
        ex(c),
        ex(d),
        ex(e),
        ex(d),
        ex(a),
        ex(e),
        ex(a),
        ex(b),
        ex(c),
        ex(c),
        ex(d),
        ex(a)
    ]
    normal_array = [
        n1, n1, n1, n2, n2, n2, n3, n3, n3, n4, n4, n4, n5, n5, n5, n5, n5, n5
    ]

    # Return VBO Object
    return VBObject(_vbo.VBO(_array(vertex_array, 'f')),
                    _vbo.VBO(_array(normal_array, 'f')), len(vertex_array))
Esempio n. 34
0
def load_gmsh_model(modelfile,
                    scale,
                    dx=0.0,
                    dy=0.0,
                    dz=0.0,
                    avg=True,
                    neg_normal=False,
                    texture=None):
    """
    Loads an .MSH or .GMSH file and returns an vboObject scaled as 'scale', by default
    normal are average, to disable use avg=False. The model also can be displaced by
    (dx,dy,dz) and reverse the normals if neg_normal is True.

    :param modelfile: File name
    :param scale: Scale parameter
    :param dx: X-displacement
    :param dy: Y-displacement
    :param dz: Z-displacement
    :param avg: Normal-avg
    :param neg_normal: Reverse normal
    :param texture: Texture file
    :type modelfile: basestring
    :type scale: float
    :type dx: float, int
    :type dy: float, int
    :type avg: bool
    :type neg_normal: bool
    :type texture: list
    :return: VBO Object that contains GMSH model
    :rtype: VBObject
    """
    def load(gmshfile, _scale, _dx, _dy, _dz):
        """
        Load an GMSH file and returns 3 lists, one for vertex, one for normals and another for
        normal averages. Takes file, scale and displacement.
        :param gmshfile: GMSH file
        :param _scale: Scale parameter
        :param _dx: X-displacement
        :param _dy: Y-displacement
        :param _dz: Z-displacement
        :return:
        """
        def get_ave_normals(_nodes, _elems):
            """
            Calculate normal average for each vertex
            :param _nodes:
            :param _elems:
            :return:
            """
            nodetrilist = []
            for _nodenum in range(len(_nodes)):
                nodetrilist.append([])
                for elemnum in range(len(_elems)):
                    if _nodenum in _elems[elemnum]:
                        nodetrilist[_nodenum].append(elemnum)
            _avenorms = []

            for tri in nodetrilist:
                ave_ni = 0.0
                ave_nj = 0.0
                ave_nk = 0.0
                denom = max(float(len(tri)), 1)
                for _elem in tri:
                    _vert1 = [
                        _nodes[_elems[_elem][0]][0],
                        _nodes[_elems[_elem][0]][1],
                        _nodes[_elems[_elem][0]][2]
                    ]
                    _vert2 = [
                        _nodes[_elems[_elem][1]][0],
                        _nodes[_elems[_elem][1]][1],
                        _nodes[_elems[_elem][1]][2]
                    ]
                    _vert3 = [
                        _nodes[_elems[_elem][2]][0],
                        _nodes[_elems[_elem][2]][1],
                        _nodes[_elems[_elem][2]][2]
                    ]
                    _normals = get_normals(_vert1, _vert2, _vert3)
                    ave_ni += _normals[0]
                    ave_nj += _normals[1]
                    ave_nk += _normals[2]
                _avenorms.append(
                    [ave_ni / denom, ave_nj / denom, ave_nk / denom])
            return _avenorms

        def get_normals(vert_a, vert_b, vert_c):
            """
            Calculate normal each 3 vertex
            :param vert_a:
            :param vert_b:
            :param vert_c:
            :return:
            """
            x_a = vert_a[0]
            x_b = vert_b[0]
            x_c = vert_c[0]
            y_a = vert_a[1]
            y_b = vert_b[1]
            y_c = vert_c[1]
            z_a = vert_a[2]
            z_b = vert_b[2]
            z_c = vert_c[2]
            a_bx = x_b - x_a
            a_by = y_b - y_a
            a_bz = z_b - z_a
            b_cx = x_c - x_b
            b_cy = y_c - y_b
            b_cz = z_c - z_b
            nx = a_by * b_cz - a_bz * b_cy
            ny = a_bz * b_cx - a_bx * b_cz
            nz = a_bx * b_cy - a_by * b_cx
            vec_mag = _sqrt(nx**2 + ny**2 + nz**2)
            ni = nx / vec_mag
            nj = ny / vec_mag
            nk = nz / vec_mag
            return [ni, nj, nk]

        # Read file
        try:
            infile = open(gmshfile)
        except:
            raise Exception('Model file does not exist')

        # Create model
        nodes = []
        try:
            gmshlines = infile.readlines()
            readnodes = False
            readelems = False
            skipline = 0
            elems = []
            lnum = 0
            for line in gmshlines:
                if '$Nodes' in line:
                    readnodes = True
                    skipline = 2
                    nnodes = int(gmshlines[lnum + 1].strip())
                    nodes = []
                    for _i in range(nnodes):
                        nodes.append(99999.9)
                elif '$EndNodes' in line:
                    readnodes = False
                    skipline = 1
                elif '$Elements' in line:
                    readelems = True
                    skipline = 2
                elif '$EndElements' in line:
                    readelems = False
                    skipline = 1
                if skipline < 1:
                    if readnodes:
                        n_xyz = line.strip().split()
                        nodenum = int(n_xyz[0]) - 1
                        n_x = float(n_xyz[1]) * _scale + _dx
                        n_y = float(n_xyz[2]) * _scale + _dy
                        n_z = float(n_xyz[3]) * _scale + _dz
                        if neg_normal:
                            n_z *= -1
                        nodes[nodenum] = [n_x, n_y, n_z]
                    elif readelems:
                        n123 = line.split()
                        if n123[1] == '2':
                            n1 = int(n123[-3]) - 1
                            n2 = int(n123[-1]) - 1
                            n3 = int(n123[-2]) - 1
                            elems.append([n1, n2, n3])
                else:
                    skipline -= 1
                lnum += 1
            triarray = []
            normarray = []
            avenorms = []
            nodeavenorms = get_ave_normals(nodes, elems)
            for elem in elems:
                vert1 = [
                    nodes[elem[0]][0], nodes[elem[0]][1], nodes[elem[0]][2]
                ]
                vert2 = [
                    nodes[elem[1]][0], nodes[elem[1]][1], nodes[elem[1]][2]
                ]
                vert3 = [
                    nodes[elem[2]][0], nodes[elem[2]][1], nodes[elem[2]][2]
                ]
                avenorm0 = nodeavenorms[elem[0]]
                avenorm1 = nodeavenorms[elem[1]]
                avenorm2 = nodeavenorms[elem[2]]
                normals = get_normals(vert1, vert2, vert3)
                triarray.append(vert1)
                triarray.append(vert2)
                triarray.append(vert3)
                normarray.append(normals)
                normarray.append(normals)
                normarray.append(normals)
                avenorms.append(avenorm0)
                avenorms.append(avenorm1)
                avenorms.append(avenorm2)
            return triarray, normarray, avenorms

        except:
            raise Exception('Error load model')

    vertex, norm, avgnorm = load(modelfile, scale, float(dx), float(dy),
                                 float(dz))
    if avg:
        return VBObject(_vbo.VBO(_array(vertex, 'f')),
                        _vbo.VBO(_array(avgnorm, 'f')), len(vertex), texture)
    else:
        return VBObject(_vbo.VBO(_array(vertex, 'f')),
                        _vbo.VBO(_array(norm, 'f')), len(vertex), texture)
Esempio n. 35
0
    def note(self):
        '''
        Summary
        ====
        Print chapter15.1 note

        Example
        ====
        ```python
        Chapter15_1().note()
        ```
        '''
        print('chapter15.1 note as follow')
        print('第四部分 高级设计和分析技术')
        print('这一部分将介绍设计和分析高效算法的三种重要技术:动态规划(第15章),贪心算法(第16章)和平摊分析(第17章)')
        print('本书前面三部分介绍了一些可以普遍应用的技术,如分治法、随机化和递归求解')
        print('这一部分的新技术要更复杂一些,但它们对有效地解决很多计算问题来说很有用')
        # !动态规划适用于问题可以分解为若干子问题,关键技术是存储这些子问题每一个解,以备它重复出现
        print('动态规划通常应用于最优化问题,即要做出一组选择以达到一个最优解。',
              '在做选择的同时,经常出现同样形式的子问题。当某一特定的子问题可能出自于多于一种选择的集合时,动态规划非常有效')
        print(' 关键技术是存储这些子问题每一个解,以备它重复出现。第15章说明如何利用这种简单思想,将指数时间的算法转化为多项式时间的算法')
        print('像动态规划算法一样,贪心算法通常也是应用于最优化问题。在这种算法中,要做出一组选择以达到一个最优解。')
        print(' 采用贪心算法可以比用动态规划更快地给出一个最优解。但是不同意判断贪心算法是否一定有效。')
        print(' 第16章回顾拟阵理论,它通常可以用来帮助做出这种判断。')
        print('平摊分析是一种用来分析执行一系列类似操作的算法的工具。', '平摊分析不仅仅是一种分析工具,也是算法设计的一种思维方式,',
              '因为算法的设计和对其运行时间的分析经常是紧密相连的')
        print('第15章 动态规划')
        print('和分治法一样,动态规划是通过组合子问题的解而解决整个问题的')
        print('分治法算法是指将问题划分成一些独立的子问题,递归地求解各子问题,然后合并子问题的解而得到原问题的解')
        print('于此不同,动态规划适用于子问题不是独立的情况,也就是各子问题包含的公共的子子问题。')
        print('动态规划不需要像分治法那样重复地求解子子问题,对每个子子问题只求解一次,将其结果保存在一张表中')
        print('动态规划通常应用于最优化问题。此类问题可能有很多种可行解。每个解有一个值,希望找出一个具有最优(最大或最小)值的解')
        print('动态规划算法的设计可以分为如下4个步骤:')
        print(' 1.描述最优解的结构')
        print(' 2.递归定义最优解的值')
        print(' 3.按自底向上的方式计算最优解的值')
        print(' 4.由计算出的结果构造一个最优解')
        print('第1~3步构成问题的动态规划解的基础。第4步在只要求计算最优解的值时可以略去')
        print('15.1 装配线调度')
        print('一个动态规划的例子是求解一个制造问题')
        print('某汽车公司在有两条装配线的工厂内生产汽车,一个汽车底盘在进入每一条装配线后,在一些装配站中会在底盘上安装部件')
        print('然后,完成的汽车在装配线的末端离开。每一条装配线上有n个装配站,编号为j=1,2..,n')
        print(
            '将装配线i(i为1或2)的第j个装配站表示为Si,j。装配线1的第j个站(S1,j)和装配线2的第j个站(S2,j)执行相同的功能'
        )
        print('然而,这些装配站是在不同的时间建造的,并且采用了不同的技术;因此在每个站上所需的时间是不同的')
        print('在不同站所需要的时间为aij,一个汽车底盘进入工厂,然后进入装配线i(i为1或2),花费时间ei.')
        print('在通过一条线的第j个装配站后,这个底盘来到任一条线的第(j+1)个装配站')
        print('如果它留在相同的装配线,则没有移动的开销;但是,如果在装配站Sij后,它移动了另一条线上,则花费时间为tij')
        print(
            '在离开一条线的第n个装配站后,完成的汽车花费时间xi离开工厂。待求解的问题是确定应该在装配线1内选择哪些站、在装配线2内选择哪些站'
        )
        print('才能使汽车通过工厂的总时间最小')
        print('显然,当有很多个装配站时,用强力法(brute force)来极小化通过工厂装配线的时间是不可能的。')
        print('如果给定一个序列,在装配线1上使用哪些站,在装配线2上使用哪些站,则可以在Θ(n)时间内,',
              '很容易计算出一个底盘通过工厂装配线要花的时间')
        print('不幸地是,选择装配站的可能方式有2^n种;可以把装配线1内使用的装配站集合看作{1,2,..,n}的一个子集')
        print(
            '因此,要通过穷举所有可能的方式、然后计算每种方式花费的时间来确定最快通过工厂的路线,需要Ω(2^n)时间,这在n很大时是不行的')
        print('步骤1.通过工厂最快路线的结构,子问题最优结果结果的存储空间')
        print(' 动态规划方法的第一个步骤是描述最优解的结构的特征。对于装配线调度问题,可以如下执行。')
        print(
            ' 首先,假设通过装配站S1,j的最快路线通过了装配站S1,j-1。关键的一点是这个底盘必定是利用了最快的路线从开始点到装配站S1,j-1的'
        )
        print(' 更一般地,对于装配线调度问题,一个问题的最优解包含了子问题的一个最优解。')
        print(' 我们称这个性质为最优子结构,这是是否可以应用动态规划方法的标志之一')
        print(' 为了寻找通过任一条装配线上的装配站j的最快路线,我们解决它的子问题,即寻找通过两条装配线上的装配站j-1的最快路线')
        print(' 所以,对于装配线调度问题,通过建立子问题的最优解,就可以建立原问题某个实例的一个最优解')
        print('步骤2.一个递归的解,总时间最快就是子问题最快')
        print(' 在动态规划方法中,第二个步骤是利用子问题的最优解来递归定义一个最优解的值。')
        print(' 对于装配线的调度问题,选择在两条装配线上通过装配站j的最快路线的问题来作为子问题')
        print(' j=1,2,...,n。令fi[j]表示一个底盘从起点到装配站Sij的最快可能时间')
        print(' 最终目标是确定底盘通过工厂的所有路线的最快时间,记为f')
        print(' 底盘必须一路径由装配线1或2通过装配站n,然后到达工厂的出口,由于这些路线的较快者就是通过整个工厂的最快路线')
        print(' f=min(f1[n]+x1,f2[n]+x2)')
        print(' 要对f1[1]和f2[1]进行推理也是容易的。不管在哪一条装配线上通过装配站1,底盘都是直接到达该装配站的')
        print('步骤3.计算最快时间fxin')
        print(' 此时写出一个递归算法来计算通过工厂的最快路线是一件简单的事情,',
              '这种递归算法有一个问题:它的执行时间是关于n的指数形式')
        # !装配站所需时间
        a = [[7, 9, 3, 4, 8, 4],\
             [8, 5, 6, 4, 5, 7]]
        # !装配站切换到另一条线花费的时间
        t = [[2, 3, 1, 3, 4],\
             [2, 1, 2, 2, 1]]
        # !进入装配线所需时间
        e = [2, 4]
        # !离开装配线所需时间
        x = [3, 2]
        # !每条装配线装配站的数量
        n = 6
        result = self.fastway(a, t, e, x, n)
        fxin = result[0]
        lxin = result[1] + 1
        print('fxin:', fxin, ' lxin:', lxin, 'l[lxin]:',
              _array(self.l)[lxin - 1] + 1)
        print('最优路径输出(降序从尾到头)')
        self.printstations(self.l, lxin, n)
        print('存储的子问题的解为:')
        print('f:')
        print(_array(self.f))
        print('l:')
        print(_array(self.l) + 1)
        print('步骤4.构造通过工厂的最快路线lxin')
        print('练习15.1-1 最优路径输出(升序从头到尾)')
        # 通过递归的方式先到达路径头
        self.printstations_ascending(self.l, lxin, n)
        print('练习15.1-2 定理:在递归算法中引用fi[j]的次数ri(j)等于2^(n-j)')
        print('练习15.1-3 定理:所有引用fi[j]的总次数等于2^(n+1)-2')
        print('练习15.1-4 包含fi[j]和li[j]值的表格共含4n-2个表项。说明如何把空间需求缩减到共2n+2')
        print('练习15.1-5 略')
Esempio n. 36
0
class Quad8(_Element):
    nodes = 8
    dimensions = 2
    edges = _array([[0, 1, 4], [1, 2, 5], [2, 3, 6], [3, 0, 7]])
Esempio n. 37
0
class Quad4(_Element):
    nodes = 4
    dimensions = 2
    edges = _array([[0, 1], [1, 2], [2, 3], [3, 0]])
Esempio n. 38
0
def blobs2features(blobs, min_hypot=0, min_theta=-pi, max_theta=pi, min_ratio=0, max_ratio=1):
    """ Generate a stream of features conforming to limits.
    
        Yields 5-element tuples: indexes for three blobs followed by feature ratio, theta.
    """
    count = len(blobs)
    
    # one-dimensional arrays of simple positions
    xs = _array([blob.x for blob in blobs], dtype=float)
    ys = _array([blob.y for blob in blobs], dtype=float)
    
    #
    # two-dimensional arrays of component distances between each blob
    #   dx = b.x - a.x, dy = b.y - a.y
    #
    xs_ = repeat(reshape(xs, (1, count)), count, 0)
    ys_ = repeat(reshape(ys, (1, count)), count, 0)
    dxs, dys = transpose(xs_) - xs_, transpose(ys_) - ys_
    
    #
    # two-dimensional array of distances between each blob
    #   distance = sqrt(dx^2 + dy^2)
    #
    distances = nsqrt(dxs ** 2 + dys ** 2)
    
    #
    # Make a list of eligible eligible blob pairs
    #
    hypoteni = distances.copy()
    hypoteni[distances < min_hypot] = 0
    
    hypot_nonzero = nonzero(hypoteni)

    ## Prepend separation distance, longest-to-shortest
    #blobs_sorted = [(distances[i,j], i, j) for (i, j) in zip(*hypot_nonzero)]
    
    # Prepend combined pixel size, largest-to-smallest
    blobs_sorted = [(blobs[i].size + blobs[j].size, i, j) for (i, j) in zip(*hypot_nonzero)]

    blobs_sorted.sort(reverse=True)
    
    #
    # check each hypotenuse for an eligible third point
    #
    for (row, (sort_value, i, j)) in enumerate(blobs_sorted):
        #
        # vector theta for hypotenuse (i, j)
        #
        ij_theta = _atan2(dys[i,j], dxs[i,j])
        
        #
        # rotate each blob[k] around blob[i] by -theta, to get a hypotenuse-relative theta for (i, k)
        #
        ik_xs = dxs[i,:] * _cos(-ij_theta) - dys[i,:] * _sin(-ij_theta)
        ik_ys = dxs[i,:] * _sin(-ij_theta) + dys[i,:] * _cos(-ij_theta)
        
        ik_thetas = arctan2(ik_ys, ik_xs)

        ik_thetas = [(blobs[k].size, k, theta) for (k, theta) in enumerate(ik_thetas)]
        ik_thetas.sort(reverse=True)
        
        #
        # check each blob[k] for correct distance ratio
        #
        for (size, k, theta) in ik_thetas:
            ratio = distances[i,k] / distances[i,j]
            
            if theta < min_theta or max_theta < theta:
                continue

            if ratio < min_ratio or max_ratio < ratio:
                continue
            
            if i == j or i == k or j == k:
                continue
            
            yield (i, j, k, ratio, theta)