def main():
    starLength = 1024
    universe = Universe(starLength)
    universe.generateStars()
    universe.printUniverse()

    print("==========")

    probe = Probe()

    # calculating probe distant to stars
    for i in range(len(universe.StarList)):
        dist = ((probe._x - universe.StarList[i]._x)**2 +
                (probe._y - universe.StarList[i]._y)**2 +
                (probe._z - universe.StarList[i]._z) * 2)**0.5
        universe.StarList[i].probeDistant = dist

    universe.StarList.sort(
        key=lambda c: c.probeDistant)  # to see which star is close to probe

    counter = 1
    x = probe.nextStar(universe.StarList)

    while (counter != starLength + 1 and x != True):
        universe.StarList.sort(key=lambda c: c.probeDistant)
        counter += 1
        x = probe.nextStar(universe.StarList)

    if (counter == 1024 or x == None):
        print("Could not find a life or there is no life at the universe.")
    pass
예제 #2
0
def analyzePacket(packet):
    """Callback when sniffing a packet. This function send the relevant probes to the WiFace API

    Args:
        packet : sniffed packet
    """
    if packet.haslayer(Dot11) or packet.haslayer(Dot11FCS):
        if packet.type == 0 and packet.subtype == 4:
            address = packet.addr2
            if address not in mac_dic or (datetime.utcnow() - mac_dic[address]) / timedelta(seconds=1) > 60 and estimateDistance(packet.dBm_AntSignal, -30) < 20:
                mac_dic[address] = datetime.utcnow()
                print(estimateDistance(packet.dBm_AntSignal, -25), "m estimés")
            else:
                return
            try:
                ret_mac = MyAPI.getMACByAddress(address)
            except APIErrorNotFound:
                try:
                    vendor = MAC.extractVendor(address.upper())
                    vendor = vendor if MyAPI.getVendorByOUI(vendor) else "UNDEF"
                    mac = MAC(address.upper(), MAC.isRandomFunc(address), vendor)
                    ret_mac = MyAPI.postMAC(mac)
                except Exception as e:
                    print(e)
                    return
            except APIError:
                return

            probe = Probe(packet.info.decode('utf-8'), 1, ret_mac.address)
            MyAPI.postProbeRequest(probe)
            print("SSID: ", packet.addr2)
            print("ESSID : ", packet.info.decode('utf-8'))
예제 #3
0
    def addBlock(self, type, argN=0, methodType=None):
        if type == "class":
            blocks.append(
                Block(type + str(self.classCount), type, "Add Caption",
                      self.classCount, 0))
            self.classCount += 1
            d = class_Block(self)
            d.set_name(blocks[len(blocks) - 1])
        elif type == "method":
            blocks.append(
                Block(methodType + str(self.methodCount), type, "Add Caption",
                      self.methodCount, 0))
            self.methodCount += 1
            d = method_Block(self)
            d.set_name(blocks[len(blocks) - 1])
        elif type == "variable":
            blocks.append(
                Block(type + str(self.variableCount), type, "Add Caption",
                      self.variableCount, 0))
            self.variableCount += 1
            d = variable_Block(self)
            d.set_name(blocks[len(blocks) - 1])
        elif type == "output":
            blocks.append(
                Block(type + str(self.outputCount), type, "Add Caption",
                      self.outputCount, 0))
            self.outputCount += 1
            d = output_Block(self)
            d.set_name(blocks[len(blocks) - 1])
        elif type == "probe":
            blocks.append(Probe())
            self.probeCount += 1
            d = probe_Block(self)
        else:
            print("Error with request")
            pass

        s = Scatterer()
        self.add_widget(s)
        s.set_name(blocks[len(blocks) - 1])
        if type == "method":
            d.tailorMethod(argN, methodType)
        elif type == "probe":
            d.spawnProbe()
        scatterStack.append(s)
        widgetStack.append(d)
        s.add_widget(d)
예제 #4
0
    def postProbeRequest(self, probe):
        """API request to post a new Probe object on the WiFace API

        Arguments:
            probe {[Probe]} -- [Probe to post]

        Raises:
            APIError: [request error]

        Returns:
            [Probe] -- [Probe created on the server]
        """
        self.getTokens()
        api_url = '{0}probes'.format(self.api_url_base)
        probe_json = {'fk_mac': probe.fk_mac, 'fk_place': probe.fk_place, 'ssid': probe.ssid}
        response = self.session.post(api_url, json=probe_json)
        loaded_json = json.loads(response.text)
        probe = Probe(loaded_json.get("ssid"), loaded_json.get("fk_place"), loaded_json.get("fk_mac"))
        return probe
예제 #5
0
    def readProbes(self, maxlength=5000):
        prbs = defaultdict(list)
        # (self, sid ,  dtime, scode = 13,latitude, longitude, altitude, spd, hding):
        for i in range(maxlength):
            line = self.file.readline()
            if line:
                # '3496,6/12/2009 6:12:49 AM,13,51.496868217364,9.38602223061025,200,23,339\n'
                ftrs = line.split(',')
                sid = int(ftrs[0])
                # 3496
                dtt1 = ftrs[1].split()
                # [6/12/2009, 6:12:49, AM]
                dt2 = dtt1[0].split('/')
                # [6,12,2009]
                d = date(int(dt2[2]), int(dt2[0]), int(dt2[1]))

                tt3 = dtt1[1].split(':')
                # [6,12,49]
                if dtt1[-1] == 'AM' or int(tt3[0]) == 12:
                    t = time(int(tt3[0]), int(tt3[1]), int(tt3[2]))
                elif dtt1[-1] == 'PM':
                    t = time(int(tt3[0]) + 12, int(tt3[1]), int(tt3[2]))
                else:
                    continue
                dt = datetime.combine(d, t)
                # scode = int(ftrs[2])
                # latitude = float(ftrs[3])
                # longitude = float(ftrs[4])
                # altitude = float(ftrs[5])
                # spd = float(ftrs[6])
                prb = Probe(sid, dt, int(ftrs[2]), float(ftrs[3]),
                            float(ftrs[4]), float(ftrs[5]), float(ftrs[6]),
                            float(ftrs[7]))
                prbs[sid].append(prb)
            else:
                return prbs

        return prbs
예제 #6
0
class FastSASA:
    timer = Timer()

    def __init__(self, probe_points=100, probe_radius=1.4):
        self.PDB = PDB()
        self.probe = Probe(self.PDB.get_atoms(), probe_points, probe_radius)

    def sasa(self, report=''):
        self.get_neighbor_probe_points()
        self.calc_sasa()
        self.sum_sasa(self.PDB.structure)
        self.report_sasa(report)

    def get_neighbor_probe_points(self):
        self.timer.start()
        print('----------\nFinding Neighbor Probe Points', end='\r')
        atoms_points = self.probe.get_points_in_atom_probe(
            self.PDB.get_atoms())
        for atom, points in enumerate(atoms_points):
            self.probe.atoms[atom].probe.buried[points %
                                                self.probe.points] = True
            print('Searching in Atom #%s Radius' % (atom + 1), end='\r')
        print('Neighbor Probe Points Found Successfully')
        self.timer.stop()

    def calc_sasa(self):
        self.timer.start()
        print('----------\nBegin SASA Calculation', end='\r')
        for index, atom in enumerate(self.PDB.get_atoms()):
            pp = self.probe.points
            atom_probe_points = self.probe.atoms[index].probe.buried
            atom.accessibility = sum([not p for p in atom_probe_points]) / pp
            atom.size = 4 * np.pi * (atom.radius + self.probe.radius)**2
            atom.sasa = atom.accessibility * atom.size
            print('Atom #%s [%s] SASA is %s Å' %
                  (index + 1, atom.element, atom.sasa),
                  end='\r')
        print('SASA Calculated Successfully')
        self.timer.stop()

    def sum_sasa(self, item):
        if hasattr(item, 'sasa'):
            return item.sasa, item.size, item.accessibility
        else:
            total_sasa, total_size = 0, 0
            for i in item.get_list():
                item_sasa, item_size, _ = self.sum_sasa(i)
                total_sasa += item_sasa
                total_size += item_size
            item.sasa = total_sasa
            item.size = item.RSA if hasattr(item, 'RSA') else total_size
            item.accessibility = item.sasa / item.size * 100
            return item.sasa, item.size, item.accessibility

    def report_sasa(self, method=''):
        print('----------\nResult :\n')
        for model in self.PDB.structure:
            if method.__contains__('m'):
                t, _, a = map(round, self.sum_sasa(model), [2] * 3)
                print('Model #%s SASA is %s Å (%s%%)' % (model.id, t, a))
            for chain in model:
                if method.__contains__('c'):
                    t, _, a = map(round, self.sum_sasa(chain), [2] * 3)
                    print('Chain #%s SASA is %s Å (%s%%)' % (chain.id, t, a))
                for residue in chain:
                    if method.__contains__('r'):
                        t, _, a = map(round, self.sum_sasa(residue), [2] * 3)
                        print(
                            'Residue %s #%s SASA is %s Å (%s%%)' %
                            (residue.get_resname(), residue.get_id()[1], t, a))
                    for atom in residue:
                        if method.__contains__('a'):
                            print('Atom #%s SASA is %s Å [Polar : %s]' %
                                  (atom.get_name(), atom.sasa, atom.polar))
        t, _, a = map(round, self.sum_sasa(self.PDB.structure), [2] * 3)
        print('Total SASA of %s is %s Å (%s%%)\n' %
              (self.PDB.structure.get_id(), t, a))

    def residue_neighbors(self, model, chain, residue):
        item = self.PDB.get_item(model, chain, residue)
        if item is None:
            print(
                '----------\nError Getting Residue Neighbors :\nResidue not Found\n'
            )
            return None
        neighbors = self.get_residue_neighbors(item)
        self.report_residue_neighbors(item, neighbors)

    def get_residue_neighbors(self, residue, quiet=False):
        atoms = self.PDB.get_atoms(residue)
        atoms = self.get_atoms_neighbors(atoms, quiet)
        if not quiet:
            self.timer.start()
            print('----------\nBegin Residue Neighbor Search', end='\r')
        residue.neighbors = {}
        for atom in atoms:
            neighbor_residues = [
                n.get_parent() for n in atom.neighbors
                if n.get_parent() is not residue
            ]
            for neighbor_residue in list(
                    OrderedDict.fromkeys(neighbor_residues)):
                chain = neighbor_residue.get_parent()
                model = chain.get_parent()
                if neighbor_residue != residue:
                    if residue.neighbors.get(model.id) is None:
                        residue.neighbors[model.id] = {}
                    if residue.neighbors[model.id].get(chain.id) is None:
                        residue.neighbors[model.id][chain.id] = []
                    residue.neighbors[model.id][chain.id].append(
                        neighbor_residue.id[1])
        for model in residue.neighbors:
            for chain in residue.neighbors[model]:
                residue.neighbors[model][chain] = list(
                    OrderedDict.fromkeys(residue.neighbors[model][chain]))
        if not quiet:
            print('Residue Neighbors Found Successfully')
            self.timer.stop()
        return residue.neighbors

    def get_atoms_neighbors(self, atoms, quiet=False):
        if not quiet:
            self.timer.start()
            print('----------\nBegin Atom Neighbor Search', end='\r')
        atoms_points = self.probe.get_points_in_atom_probe(atoms)
        for index, atom_points in enumerate(atoms_points):
            atoms[index].neighbors = [
                self.probe.atoms[atom]
                for atom in atom_points // self.probe.points
            ]
        if not quiet:
            print('Atom Neighbors Found Successfully')
            self.timer.stop()
        return atoms

    def report_residue_neighbors(self, item, neighbors):
        print('----------\nResult :\n')
        print('Selected Residue is %s #%s\n' %
              (item.get_resname(), item.id[1]))
        for model in neighbors:
            print('Model #%s : ' % model)
            for chain in neighbors[model]:
                print('Chain %s : [' % chain, end='')
                for residue in neighbors[model][chain]:
                    print('%s #%s ,' % (self.PDB.get_item(
                        model, chain, residue).get_resname(), residue),
                          end='')
                print('\b\b]')
        print('')

    def chain_neighbors(self, model, chain):
        item = self.PDB.get_item(model, chain)
        if item is None:
            print(
                '----------\nError Getting Chain Neighbors :\nChain not Found\n'
            )
            return None
        neighbors = self.get_chain_neighbors(item)
        self.report_chain_neighbors(model, chain, neighbors)

    def get_chain_neighbors(self, chain):
        self.timer.start()
        print('----------\nSearching Chain Neighbors', end='\r')
        chain.neighbors = {}
        for residue in chain.get_residues():
            print('Getting Residue #%s Neighbors' % residue.id[1], end='\r')
            neighbors = self.get_residue_neighbors(residue,
                                                   True)[chain.get_parent().id]
            if neighbors is not None and len(neighbors) > 1:
                ch = residue.get_parent()
                for neighbor in [
                        key for key in neighbors.keys() if key is not ch.id
                ]:
                    if ch.neighbors.get(neighbor) is None:
                        ch.neighbors[neighbor] = {}
                    if len(neighbors[neighbor]):
                        ch.neighbors[neighbor][
                            residue.id[1]] = neighbors[neighbor][0]
        for neighbor in chain.neighbors:
            temp = {val: key for key, val in chain.neighbors[neighbor].items()}
            chain.neighbors[neighbor] = {val: key for key, val in temp.items()}
        print('Chain Neighbors Found Successfully')
        self.timer.stop()
        return chain.neighbors

    def report_chain_neighbors(self, model, selected_chain, neighbors):
        print('----------\nResult :\n')
        print('Selected Chain is %s \n' % selected_chain)
        for chain in neighbors:
            counter = 0 if len(neighbors[chain]) > 3 else 1
            print('Chain %s :  [' % chain, end='')
            for own_residue in neighbors[chain]:
                if counter % 3 == 0:
                    print('', end='\n\t')
                counter += 1
                neighbor = neighbors[chain][own_residue]
                own_residue_name = self.PDB.get_item(
                    model, selected_chain, own_residue).get_resname()
                neighbor_name = self.PDB.get_item(model, chain,
                                                  neighbor).get_resname()
                print('%s #%s -> %s #%s ,' %
                      (own_residue_name, own_residue, neighbor_name, neighbor),
                      end='')
            print('\b\b]')
        print('')

    def critical_residues(self, threshold, model, chain):
        if not hasattr(self.PDB.structure, 'sasa'):
            self.sasa()
        item = self.PDB.get_item(model, chain)
        if item is None:
            print(
                '----------\nError Getting Chain Neighbors :\nChain not Found\n'
            )
            return None
        critical_residues = self.get_critical_residues(threshold, model, chain,
                                                       item)
        self.report_critical_residues(critical_residues, chain)

    def get_critical_residues(self, threshold, model, chain, item):
        self.timer.start()
        print('----------\nSearching For Critical Residues', end='\r')
        critical_residues = []
        residues = item.get_residues()
        for residue in residues:
            if residue.accessibility > threshold:
                continue
            print('Checking Residue #%s Neighbors' % residue.id[1], end='\r')
            neighbors = self.get_residue_neighbors(residue, True)
            equal, non = [], []
            for r in neighbors[model][chain]:
                res = self.PDB.get_item(model, chain, r)
                if res.polar == residue.polar:
                    equal.append(r)
                else:
                    non.append(r)
            if residue.polar:
                if len(equal) == 0:
                    critical_residues.append({
                        'residue': residue,
                        'type': 'HydPhl-HydPhb',
                        'neighbors': non
                    })
                else:
                    critical_residues.append({
                        'residue': residue,
                        'type': 'HydPhl-HydPhl',
                        'neighbors': equal
                    })
            else:
                if len(non) == 0:
                    critical_residues.append({
                        'residue': residue,
                        'type': 'HydPhb-HydPhb',
                        'neighbors': equal
                    })
        print('Critical Residues Found Successfully')
        self.timer.stop()
        return critical_residues

    @staticmethod
    def report_critical_residues(items, selected_chain):
        print('----------\nResult :\n')
        print('Selected Chain is %s \n' % selected_chain)
        items_types_list = [i['type'] for i in items]
        print(
            '%s Critical Residues Found : %s HydPhl-HydPhl - %s HydPhl-HydPhb - %s HydPhb-HydPhb\n'
            % (len(items), items_types_list.count('HydPhl-HydPhl'),
               items_types_list.count('HydPhl-HydPhb'),
               items_types_list.count('HydPhl-HydPhb')))

        for item in items:
            residue = item['residue']
            print(
                'Residue %s #%s with %s %% RSA is %s with %s charge' %
                (residue.get_resname(), residue.get_id()[1],
                 round(residue.accessibility, 2), 'Hydrophilic' if
                 residue.polar else 'Hydrophobic', 'Positive' if residue.charge
                 == 1 else 'Negative' if residue.charge == -1 else 'Natural'))
            print('There are %s neighbors : %s\n' %
                  (item['type'], item['neighbors']))
        print('')
예제 #7
0
 def __init__(self, probe_points=100, probe_radius=1.4):
     self.PDB = PDB()
     self.probe = Probe(self.PDB.get_atoms(), probe_points, probe_radius)
예제 #8
0
# Get session data
session_id = 791319847
session, probes, channels = getSessionData(cache, session_id)

# Get all flash start and end times
flashTable = session.get_stimulus_table("flashes")
flashTable = flashTable[flashTable['color']==1]
flashStarts, flashEnds = [], []
for index, row in flashTable.iterrows():
    flashStarts.append(row['start_time'])
    flashEnds.append(row['stop_time'])

# Define period for analysis
periodStart = flashStarts[0]-2
periodEnd = flashEnds[2]+2

# Get probes
sessionProbes = list()
for probe_id in [805008600, 805008604]:
    probe = Probe(probe_id, session_id)
    probe.getLfpData(session)
    probe.getProbeCoordinates(channels, session)
    probe.cutLFP(startTime=periodStart, endTime=periodEnd)
    sessionProbes.append(probe)
    del probe
np.save('sessionProbes', sessionProbes)

# sessionProbes = np.load('sessionProbes.npy')
# showProbe(sessionProbes[0])