Ejemplo n.º 1
0
def fitness(position):
    key = "".join(alphabet[i] for i in position)
    substitution = Substitution(alphabet, key)
    original_text = substitution.decrypt(cyphertext)
    frequency = Frequency(n_gram, alphabet)
    frequency.get_frequency(original_text)
    res = 0
    for i in range(len(n_gram)):
        for j in range(len(frequency.ftab[i])):
            res += alpha[i] * abs(frequency.ftab[i][j] - target.ftab[i][j])
    return res
Ejemplo n.º 2
0
def incidenceOfCoincidence(sequence):
    if (len(sequence) > 1):
      F = Frequency()
      F.count(sequence)
      IncOfCoinc = 0
      FreqNum = 0
      length = len(sequence)
      for i in range(0,26):
        FreqNum = F.getNthNum(i)
        IncOfCoinc = IncOfCoinc + (FreqNum*(FreqNum - 1))
      IncOfCoinc = (IncOfCoinc / (length*(length - 1)))
      return IncOfCoinc
    else:
      return 0
Ejemplo n.º 3
0
def renderFrequency():

    frequency = Frequency()

    if request.method == "GET":
        return render_template('frequency.html')
    if request.method == "POST":
        frequencyDist = frequency.getFrequency(
            request.form['wine_type'],
            request.form['wine_characteristic_value'],
            request.form['wine_characteristic'], 'quality')
        return render_template('frequency-graph.html',
                               results=Markup(frequencyDist[0]),
                               wineChars=frequencyDist[1],
                               wineChar=frequencyDist[2].title())
Ejemplo n.º 4
0
def query_frequency(request):
    query = request.GET.get("query", None)
    response_data = {}
    sample = 500
    if query is not None:

        # Get Timeframe e.g. process time from request
        request_timeframe = Timeframe(start=request.GET.get("start", None),
                                      end=request.GET.get("end", None),
                                      interval=request.GET.get(
                                          "interval", "hour"))

        data = None
        try:
            # Query GNIP and get frequency
            data = Frequency(query=query,
                             sample=sample,
                             start=request_timeframe.start,
                             end=request_timeframe.end)
        except GNIPQueryError as e:
            return handleQueryError(e)

        response_data["frequency"] = data.freq
        response_data["sample"] = sample
    return HttpResponse(json.dumps(response_data),
                        content_type="application/json")
Ejemplo n.º 5
0
def incidence_of_coincidence(sequence):
    '''
    Processes and return the incidence of coincidence of a given substring of the ciphertext
    '''
    if (len(sequence) > 1):
      F = Frequency()
      F.count(sequence)
      IncOfCoinc = 0
      FreqNum = 0
      length = len(sequence)
      for i in range(0,26):
        FreqNum = F.getNthNum(i)
        IncOfCoinc = IncOfCoinc + (FreqNum*(FreqNum - 1))
      IncOfCoinc = (IncOfCoinc / (length*(length - 1)))
      return IncOfCoinc
    else:
      return 0
Ejemplo n.º 6
0
def build_huffman_tree(frequencies):
    min_heap = build_min_heap(frequencies)
    n = len(min_heap)
    for i in range(n - 1):
        left = heappop(min_heap)
        right = heappop(min_heap)
        internal_node = Frequency(None, left.freq + right.freq, left, right)
        heappush(min_heap, internal_node)
        heapify(min_heap)

    return heappop(min_heap)
Ejemplo n.º 7
0
def count_characters_from_data(data):
    freq_dict = {}
    for byte in data:
        if byte in freq_dict:
            freq_dict[byte] += 1
        else:
            freq_dict[byte] = 1

    frequencies = []
    for key, value in freq_dict.items():
        frequencies.append(Frequency(key, value, None, None))
    return frequencies
Ejemplo n.º 8
0
def hfss_touchstone_2_media(filename, f_unit='ghz'):
    '''
    Creates a :class:`~skrf.media.media.Media` object from a a HFSS-style touchstone file with Gamma and Z0 comments 
    
    Parameters
    ------------
    filename : string 
        the HFSS-style touchstone file
    f_unit : ['hz','khz','mhz','ghz']
        passed to f_unit parameters of Frequency constructor
    
    Returns
    --------
    my_media : skrf.media.Media object
        the transmission line model defined by the gamma, and z0 
        comments in the HFSS file.
    
    Examples
    ----------
    >>> port1_media, port2_media = rf.hfss_touchstone_2_media('line.s2p')
    
    See Also
    ---------
    hfss_touchstone_2_gamma_z0 : returns gamma, and z0 
    '''
    f, gamma, z0 = hfss_touchstone_2_gamma_z0(filename)
    
    freq = Frequency.from_f(f)
    freq.unit = f_unit
    
    
    media_list = []
    
    for port_n in range(gamma.shape[1]):
        media_list.append(\
            Media(
                frequency = freq, 
                propagation_constant =  gamma[:, port_n],
                characteristic_impedance = z0[:, port_n]
                )
            )
        
        
    return media_list 
Ejemplo n.º 9
0
def query_frequency(request):
    query = request.GET.get("query", None)
    response_data = {}
    sample = 500
    if query is not None:
        # Get Timeframe e.g. process time from request
        request_timeframe = Timeframe(
            start=request.GET.get(
                "start", None), end=request.GET.get(
                "end", None), interval=request.GET.get(
                "interval", "hour"))
        # Query GNIP and get frequency
        data = Frequency(query=query,
                         sample=sample,
                         start=request_timeframe.start,
                         end=request_timeframe.end)
        response_data["frequency"] = data.freq
        response_data["sample"] = sample
        response = HttpResponse(
            json.dumps(response_data),
            content_type="application/json")
    response['Cache-Control'] = 'max-age=%d' % MAX_AGE
    return response
Ejemplo n.º 10
0
 def setUp(self):
     self.freq=Frequency(0.5)
Ejemplo n.º 11
0
class TestFrequency(unittest.TestCase):

    def setUp(self):
        self.freq=Frequency(0.5)

    def test_frequency(self):
        # make sure the shuffled sequence does not lose any elements

        st=time.time()

        self.freq.start()

        print '2 seconds'

        self.freq.end()

        self.freq.start()

        print '2 seconds'

        self.freq.end()

        self.freq.start()

        print '2 seconds'

        self.freq.end()

        end=time.time()

        self.assertTrue( end - st >= 2*3 )
Ejemplo n.º 12
0


from frequency import Frequency
from media import RectangularWaveguide, Media

from scipy.constants import c, micron, mil, inch, centi, milli, nano, micro,pi



# globals 


# pre-initialized classes       
        
f_wr51  = Frequency(15,22,201, 'ghz')
f_wr42  = Frequency(17.5,26.5,201, 'ghz')
f_wr34  = Frequency(22,33,201, 'ghz')
f_wr28  = Frequency(26.5,40,201, 'ghz')
f_wr22p4  = Frequency(33,50.5,201, 'ghz')
f_wr18p8  = Frequency(40,60,201, 'ghz')
f_wr14p8  = Frequency(50.5,75,201, 'ghz')
f_wr12p2  = Frequency(60,90,201, 'ghz')
f_wr10  = Frequency(75,110,201, 'ghz')
f_wr8  = Frequency(90,140,201, 'ghz')
f_wr6p5  = Frequency(110,170,201, 'ghz')
f_wr5p1  = Frequency(140,220,201, 'ghz')
f_wr4p3  = Frequency(170,260,201, 'ghz')
f_wr3p4  = Frequency(220,330,201, 'ghz')
f_wr2p8 = Frequency(260,400,201, 'ghz')
f_wr2p2 = Frequency(330,500,201, 'ghz')
Ejemplo n.º 13
0
def periodicity(df):
    """
    Frequencies higher than daily will not be available
    """
    med = np.median(np.diff(df.index.values))
    seconds = int(med.astype('timedelta64[s]').item().total_seconds())
    freq = Frequency()
    if seconds < 60:
        freq.label = "S"
        freq.scale = None
    elif seconds < 3600:
        freq.label = "T"
        freq.scale = None
    elif seconds < 86400:
        freq.label = "H"
        freq.scale = None
    elif seconds == 86400:
        freq.label = "D"
        freq.scale = 252
    elif seconds <= 604800:
        freq.label = "W"
        freq.scale = 52
    elif seconds <= 2678400:
        freq.label = "M"
        freq.scale = 12
    elif seconds <= 7948800:
        freq.label = "Q"
        freq.scale = 4
    else:  # anything lower than year is deemed as yearly
        freq.label = "A"
        freq.scale = 1
    return freq
Ejemplo n.º 14
0
		for line in reversed(open(fyle).readlines()):
			if re.search(keyword,line) != None:
				val = re.split(keyword,line)
		return float(val[-1])
	
	def make_hessFile(self,mat):   # Makes file hessian.dat
		f = open('hessian.dat','w')
		string = "" 
		for i in range(3 * self.mol.natom):
			for j in range(3 * self.mol.natom):
				string += "{: 13.7f}".format(mat[i,j])
			string += '\n'
		f.write(string)	
		f.close()

if __name__ == "__main__":
	template = open('../../extra-files/template.dat','r').read()
	hess = Hessian('../../extra-files/molecule.xyz')
	directory = 'DISPS'
	command = 'psi4'
	disp_size = 0.005
	energy_prefix = '@DF-RHF Final Energy:'
	sleep_time = 0
	hess.generate_inputs(template,disp_size,directory)
	hess.run_jobs(command,directory,sleep_time)
	newHess = hess.build_hessian(energy_prefix,disp_size,directory)
	hess.make_hessFile(newHess)
        # Call back to Project 1
	freq = Frequency('../../extra-files/hessian.dat','../../extra-files/molecule.xyz')
	freq.frequencies(freq.mol,freq.hess)
Ejemplo n.º 15
0
from frequency import Frequency, plaintext
from substitution import Substitution
import random

# Parameters
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
true_key = "BCDAEFGLKJIHOMNQPRSWVUTYZX"
n_gram = [1, 2]
alpha = [0.3, 0.7]
c0 = 0.8
c1 = 2
c2 = 2

# n_gram statistics
n_gram_files = ["english_monograms.txt", "english_bigrams.txt"]
target = Frequency(n_gram, alphabet)
target.get_frequency_from_file(n_gram_files)
# target.get_frequency(open("text_original.txt", "r").read())

read_cypher = False

originaltext = ""
cyphertext = ""
if (read_cypher):
    cyphertext = open("text_cypher.txt", "r").read()
else:
    # Create cypher text from originaltext_file
    originaltext_file = "text_original.txt"
    originaltext = plaintext(open(originaltext_file, "r").read(), alphabet)
    cyphertext = Substitution(alphabet, true_key).encrypt(originaltext)
    cyphertext_file = "text_cypher.txt"
Ejemplo n.º 16
0
def periodicity(df):
    """
    Frequencies higher than daily will not be available
    """
    med = np.median(np.diff(df.index.values))
    seconds = int(med.astype('timedelta64[s]').item().total_seconds())
    freq = Frequency()
    if seconds < 60:
        freq.label = "S"
        freq.scale = None
    elif seconds < 3600:
        freq.label = "T"
        freq.scale = None
    elif seconds < 86400:
        freq.label = "H"
        freq.scale = None
    elif seconds == 86400:
        freq.label = "D"
        freq.scale = 252
    elif seconds <= 604800:
        freq.label = "W"
        freq.scale = 52
    elif seconds <= 2678400:
        freq.label = "M"
        freq.scale = 12
    elif seconds <= 7948800:
        freq.label = "Q"
        freq.scale = 4
    else:  # anything lower than year is deemed as yearly
        freq.label = "A"
        freq.scale = 1
    return freq
Ejemplo n.º 17
0
#coding=utf-8

from frequency import Frequency

fr=Frequency(3) #execute 3 times by sec

while 1:

	fr.start()

	print 'This is executed 3x by sec'

	fr.end()