Ejemplo n.º 1
0
def plot_10m_max_winds(ncFile, targetDir, windScaleFactor=50):
    logger = PyPostTools.pyPostLogger()
    fig, ax, X, Y = prepare_plot_object(ncFile)
    st, fh, fh_int = getTimeObjects(ncFile)

    maxwnd = ncFile["MAX_WIND_SFC"]
    u = ncFile["SFC_U"]
    v = ncFile["SFC_V"]

    wndKT = Conversions.ms_to_kts(maxwnd)
    uKT = Conversions.ms_to_kts(u)
    vKT = Conversions.ms_to_kts(v)

    clevs = np.arange(10, 80, 2)
    smooth_wnd = gaussian_filter(to_np(wndKT), sigma=3)
    contours = plt.contourf(X,
                            Y,
                            smooth_wnd,
                            clevs,
                            cmap=get_cmap('rainbow'),
                            transform=ccrs.PlateCarree())
    cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
    cbar.set_label("Wind Speed (Kts)")

    SLP = to_np(ncFile["MSLP"])
    smooth_slp = gaussian_filter(SLP, sigma=3)
    levs = np.arange(950, 1050, 4)
    linesC = plt.contour(X,
                         Y,
                         smooth_slp,
                         levs,
                         colors="black",
                         transform=ccrs.PlateCarree(),
                         linewidths=1)
    plt.clabel(linesC, inline=1, fontsize=10, fmt="%i")

    plt.barbs(to_np(X[::windScaleFactor, ::windScaleFactor]),
              to_np(Y[::windScaleFactor, ::windScaleFactor]),
              to_np(uKT[::windScaleFactor, ::windScaleFactor]),
              to_np(vKT[::windScaleFactor, ::windScaleFactor]),
              transform=ccrs.PlateCarree(),
              length=6)

    plt.title("10m Wax Wind Speed (Kts), MSLP (mb)")
    plt.text(0.02,
             -0.02,
             "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.text(0.7,
             -0.02,
             "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.subplots_adjust(bottom=0.1)
    plt.savefig(targetDir + "/10m_maxwnd_F" + str(fh_int))
    plt.close(fig)
    return True
Ejemplo n.º 2
0
def appendTimeStatistics(raw_output, _CLASSIFIER, clf, timeFit, x_test, y_test):
    _timeFitLin = clf.time_fit_lin  # SS_MSMS
    _timeFitGauss = clf.time_fit_gauss  # MM:SS
    _timeFitOver = clf.time_overhead  # MSMS
    _timeTotal = _timeFitLin + _timeFitGauss + _timeFitOver

    _score = clf.score(x_test, y_test)
    _error = round((1 - _score) * 100, 2)

    _timePredict = clf.time_predict  ## SS_MSMS

    _percentGaussTotal = round((_timeFitGauss / _timeTotal) * 100, 2)
    _percentLinTotal = round((_timeFitLin / _timeTotal * 100), 2)
    _percentOverTotal = round((_timeFitOver / _timeTotal * 100), 2)

    # Bring Time data in readable format
    _timeFit = Conversions.secondsToHourMin(_timeTotal)
    _timeFitLin = Conversions.secondsToSecMilsec(_timeFitLin)
    _timeFitGauss = Conversions.secondsToMinSec(_timeFitGauss)
    _timeFitOver = Conversions.secondsToMilsec(_timeFitOver)
    _timePredict = Conversions.secondsToSecMilsec(_timePredict)

    raw_output[7].append(str(_timeTotal).replace(".", ",") + "s;")
    # raw_output[8].append(_timeFitGauss + "\t(" + str(_percentGaussTotal) + "%)" + ";")
    raw_output[8].append(_timeFitGauss + ";")
    # raw_output[9].append(_timeFitLin + "\t(" + str(_percentLinTotal) + "%)" + ";")
    raw_output[9].append(_timeFitLin + ";")
    # raw_output[10].append(_timeFitOver + "\t(" + str(_percentOverTotal) + "%)" + ";")
    raw_output[10].append(_timeFitOver + ";")
    raw_output[11].append(_timePredict + ";")
    raw_output[12].append(str(_error) + "%;")

    return raw_output
Ejemplo n.º 3
0
 def getDistance(self, user=None, latlng=None):
     """Returns the distance between two entities
        inputs: user - type: User, latlng - type: tuple
        -provided a user: return the distance from the park to the user
        -provided a latlng: return the distance from the park to the latitude and longitude point
     >>> x = Park(name = "Jerdon",state = "Washington", lat = 46.7297771, lng = -117.1817377)
     >>> u = User(name = "Jerdon", state = "Washington", addy = "Pullman")
     >>> u2 = User(name = "Jerdon", state = "Washington", addy = "Seattle")
     >>> x.getDistance(user = u)
     0.0
     >>> round(x.getDistance(user = u2),2)
     249.42
     """
     if (user != None):
         lat1 = self.lat
         lat2 = user.lat
         lng1 = self.lng
         lng2 = user.lng
     else:
         lat1 = self.lat
         lat2 = latlng[0]
         lng1 = self.lng
         lng2 = latlng[1]
     #(((lat1 - lat2)**2) + ((lng1 - lng2)**2))**0.5
     kmDist = CONV.distBetweenCoords(lat1, lng1, lat2, lng2)
     mDist = CONV.kmToMiles(kmDist)
     self.distance = round(mDist, 2)
     return mDist
def inv_mixcolumn(datalist):
    # according to the block length we do 2, 4 or 8 times the mix
    datalist_unmix = []
    for i in range(0, len(datalist) - 1, 2):
        xor = Arithmod.xor_bin_str(Conversions.int2bin_str(datalist[i]), Conversions.int2bin_str(datalist[(i + 1)]))
        m2 = Util.rotate_left(xor, R)
        m1 = Arithmod.subtract_64bits(Conversions.int2bin_str(datalist[i]), Conversions.int2bin_str(m2))
        m1 = Conversions.bin_str2int(m1)
        datalist_unmix.append(m1)
        datalist_unmix.append(m2)
    return datalist_unmix
Ejemplo n.º 5
0
def plot_dewpoint_temperature(ncFile, targetDir, windScaleFactor=50):
    logger = PyPostTools.pyPostLogger()
    fig, ax, X, Y = prepare_plot_object(ncFile)
    st, fh, fh_int = getTimeObjects(ncFile)

    TD = ncFile["TD"]
    TD_F = Conversions.C_to_F(TD)
    clevs = np.linspace(-20, 85, 36)
    norm = matplotlib.colors.BoundaryNorm(clevs, 36)

    contours = plt.contourf(X,
                            Y,
                            TD_F,
                            clevs,
                            norm=norm,
                            cmap=ColorMaps.td_colormap,
                            transform=ccrs.PlateCarree())
    cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
    cbar.set_label("Dewpoint Temperature ($^\circ$ F)")

    u = ncFile["SFC_U"]
    v = ncFile["SFC_V"]

    uKT = Conversions.ms_to_kts(u)
    vKT = Conversions.ms_to_kts(v)
    plt.barbs(to_np(X[::windScaleFactor, ::windScaleFactor]),
              to_np(Y[::windScaleFactor, ::windScaleFactor]),
              to_np(uKT[::windScaleFactor, ::windScaleFactor]),
              to_np(vKT[::windScaleFactor, ::windScaleFactor]),
              transform=ccrs.PlateCarree(),
              length=6)

    plt.title("Surface Dewpoint Temperature ($^\circ$F), Winds (kts)")
    plt.text(0.02,
             -0.02,
             "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.text(0.7,
             -0.02,
             "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.subplots_adjust(bottom=0.1)
    plt.savefig(targetDir + "/TD_F" + str(fh_int))
    plt.close(fig)
    return True
Ejemplo n.º 6
0
    def run(self):
        """ Perform Threaded Action """

        # get variables here
        path = self.path

        validExt = ["jpg","jpeg"]

        count = 0

        for root, dirs, files in os.walk(path):
            for f in files:
                if(f.lower()[f.rfind(".")+1:] in validExt):
                    self.im.append(Images.loader(root,f))
                    tmpim = Image.open(os.path.join(root,f))
                    tmpim.thumbnail((125,125))
                    tmpim = Conversions.padpiltoimage(tmpim,125,125).ConvertToBitmap()

                    self.il.Add(tmpim)
                    count += 1

                    wx.PostEvent(self.frame,ReturnFunction(count,self.id,0))

        self.imList.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
        #self.imList.SetImageList(self.il, wx.IMAGE_LIST_NORMAL)

        self.imList.InsertColumn(0,'',width=130)

        for i in range(count):
            self.imList.InsertStringItem(i,'')
            self.imList.SetItemImage(i,i)

        wx.PostEvent(self.frame, ReturnFunction("Ready...",self.id,1))
Ejemplo n.º 7
0
def decode(ciph_data, keypath, password):
    private = Keys.read_key(keypath)
    private = Keys.decipher_key(password, private)
    k = private[6]
    clear_data = decipher_data(ciph_data, private)
    file_data = Conversions.int_list2bytes(clear_data, k >> 3)
    return file_data
Ejemplo n.º 8
0
    def run(self):
        """ Perform Threaded Action """

        # get variables here
        path = self.path

        validExt = ["jpg", "jpeg"]

        count = 0

        for root, dirs, files in os.walk(path):
            for f in files:
                if (f.lower()[f.rfind(".") + 1:] in validExt):
                    self.im.append(Images.loader(root, f))
                    tmpim = Image.open(os.path.join(root, f))
                    tmpim.thumbnail((125, 125))
                    tmpim = Conversions.padpiltoimage(tmpim, 125,
                                                      125).ConvertToBitmap()

                    self.il.Add(tmpim)
                    count += 1

                    wx.PostEvent(self.frame, ReturnFunction(count, self.id, 0))

        self.imList.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
        #self.imList.SetImageList(self.il, wx.IMAGE_LIST_NORMAL)

        self.imList.InsertColumn(0, '', width=130)

        for i in range(count):
            self.imList.InsertStringItem(i, '')
            self.imList.SetItemImage(i, i)

        wx.PostEvent(self.frame, ReturnFunction("Ready...", self.id, 1))
Ejemplo n.º 9
0
def encode_with_key(file_data, keypath):
    formatted_pb = Keys.read_key(keypath)
    public = Keys.deformat_key(formatted_pb)
    k = public[6]
    clear_data = Conversions.bytes2int_list(file_data, k >> 3)
    ciph_data = cipher_data(clear_data, public)
    return ciph_data
Ejemplo n.º 10
0
def getUsrLoc(state, loc):
    """returns tuple containing latitude and longitude
        -inputs: state - type:string, loc - type:string
    """
    latlng = CONV.getLocToCoords(state, loc)
    lat = latlng[0]
    lng = latlng[1]
    return (lat, lng)
Ejemplo n.º 11
0
    def look(self, board):
        """ Additionally to parent class:
                - Populates available captures with squares pertaining to captures En Passant
        """
        self.clear_vision()
        new_row, _ = row, col = self.location

        # On their first move they are privileged with a double move should they chose it
        if not self.has_moved:
            self.steps = 2
        else:
            self.steps = 1

        # PAWNS move straight forward..
        for _ in range(self.steps):
            new_row += self.direction  # look one square ahead..
            if not Conversions.legal(new_row, col):  # if it's on the board..
                continue
            square = board.squares[new_row][col]
            if square.__class__.__name__ == 'Empty':  # ..and empty..
                self.avail_moves.add((new_row, col))  # add it to .avail_moves
            else:
                break

        # PAWNS capture diagonally..
        for i, j in self.pattern:  # for each forward-diagonal-direction..
            new_row = self.location[0] + i * self.direction  # step once
            new_col = self.location[1] + j * self.direction  # step once
            # if square is on the board..
            if not Conversions.legal(new_row, new_col):
                continue
            self.check_vision.add(
                (new_row, new_col))  # ..add coord to .check_vision
            # if the square is the en passant location..
            if board.passant_loc == (new_row, new_col):
                self.avail_captures.add(
                    (new_row, new_col))  # ..add it to .avail_captures
            square = board.squares[new_row][new_col]
            # if there is a piece there..
            if square.__class__.__name__ == 'Piece':
                if square.colour != self.colour:  # and it's an opposition piece ..
                    self.avail_captures.add(
                        (new_row, new_col))  # ..add coord to .avail_captures
                else:  # if it's an allied piece..
                    self.supporting.add(
                        (new_row, new_col))  # ..add coord to .supporting
Ejemplo n.º 12
0
def encode_no_key(file_data, keypath, k, password):
    private, public = generate_keys(k)
    private = Keys.cipher_key(password, private)
    formatted_pb = Keys.format_key(public)
    Keys.write_key(keypath, "private_key.txt", private)
    Keys.write_key(keypath, "public_key.txt", formatted_pb)

    clear_data = Conversions.bytes2int_list(file_data, k >> 3)
    ciph_data = cipher_data(clear_data, public)
    return ciph_data
Ejemplo n.º 13
0
def blake_hash(m, hash_len, key=""):
    if hash_len > 64:
        raise ValueError(
            "Blake hash does not support hash_length greater than 512 bits.")

    m = Conversions.str2bytes(m)
    key = Conversions.str2bytes(key)

    m_len = len(m)
    key_len = len(key)

    h = IV.copy()
    init_mix = int("0x0101" + hex(key_len)[2:] + hex(hash_len)[2:], 16)
    h[0] = h[0] ^ init_mix

    bytes_compressed = 0
    bytes_remaining = m_len

    if key_len > 0:
        if key_len > 128:
            key = key[:128]
        elif key_len < 128:
            key = key.zfill(128)
        m = key + m
        bytes_remaining += 128

    while bytes_remaining > 128:
        chunk = m[bytes_compressed:bytes_compressed + 128]
        bytes_compressed += 128
        bytes_remaining -= 128
        t = bytes_compressed.to_bytes(128, byteorder='big', signed=False)
        h = compress(h, chunk, t, False)

    chunk = m[bytes_compressed:]
    bytes_compressed = bytes_compressed + bytes_remaining
    chunk = chunk.zfill(128)
    t = bytes_compressed.to_bytes(128, byteorder='big', signed=False)
    h = compress(h, chunk, t, True)
    h_bytes = b''
    for c in h:
        h_bytes += c.to_bytes(8, byteorder='big', signed=False)

    return int.from_bytes(h_bytes[:hash_len], byteorder='big', signed=False)
Ejemplo n.º 14
0
def appendMiscStatsDualSvm(clf, raw_output):
    gauss_stat = str(clf.n_gauss) + " (" + str(
            round((float(clf.n_gauss) / float(clf.n_gauss + clf.n_lin) * 100), 2)) + "%);"
    lin_stat = str(clf.n_lin) + " \t(" + str(
            round((float(clf.n_lin) / float(clf.n_gauss + clf.n_lin) * 100), 2)) + "%);"
    dec_margin = str(round(clf._gauss_distance, 3)) + ";"
    lin_c = Conversions.toPowerOfTen(clf.lin_svc.C) + ";"
    gauss_c = Conversions.toPowerOfTen(clf.gauss_svc.C) + ";"
    gauss_gamma = Conversions.toPowerOfTen(clf.gauss_svc.gamma) + ";"
    try:
        n_gaussSVs = str(clf.gauss_svc.n_support_[0] + clf.gauss_svc.n_support_[1]) + ";"
    except AttributeError:
        n_gaussSVs = "0;"

    raw_output[0].append(gauss_stat)
    raw_output[1].append(lin_stat)
    raw_output[2].append(str(dec_margin).replace(".", ","))
    raw_output[3].append(lin_c)
    raw_output[4].append(gauss_c)
    raw_output[5].append(gauss_gamma)
    raw_output[6].append(n_gaussSVs)
Ejemplo n.º 15
0
def plot_precipitable_water(ncFile, targetDir, withMSLP=True):
    logger = PyPostTools.pyPostLogger()
    fig, ax, X, Y = prepare_plot_object(ncFile)
    st, fh, fh_int = getTimeObjects(ncFile)

    titleAdd = ""

    PW = Conversions.kgm2_to_in(ncFile["PW"])
    clevs = np.linspace(0, 3, 32)
    norm = matplotlib.colors.BoundaryNorm(clevs, 32)

    contours = plt.contourf(X,
                            Y,
                            PW,
                            clevs,
                            norm=norm,
                            cmap=ColorMaps.pw_colormap,
                            transform=ccrs.PlateCarree())
    cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
    cbar.set_label("Precipitable Water (in)")

    if (withMSLP):
        SLP = to_np(ncFile["MSLP"])
        smooth_slp = gaussian_filter(SLP, sigma=3)
        levs = np.arange(950, 1050, 4)
        linesC = plt.contour(X,
                             Y,
                             smooth_slp,
                             levs,
                             colors="black",
                             transform=ccrs.PlateCarree(),
                             linewidths=1)
        plt.clabel(linesC, inline=1, fontsize=10, fmt="%i")
        titleAdd += ", MSLP (mb)"

    plt.title("Precipitable Water (in)" + titleAdd)
    plt.text(0.02,
             -0.02,
             "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.text(0.7,
             -0.02,
             "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.subplots_adjust(bottom=0.1)
    plt.savefig(targetDir + "/PW_F" + str(fh_int))
    plt.close(fig)
    return True
Ejemplo n.º 16
0
    def Update(self, bitmapHandle=None, listing=None):
        """ Updates the Labelled Image using the current parameters and
            Listing is a tuple that provides the imlist handle and index"""

        bmp = Conversions.piltoimage(self.thumbX.copy()).ConvertToBitmap()
        bmp = TEXT.write(self.dateText,bmp,self.align,self.font,self.fontcolor,self.position)

        if(bitmapHandle):
            bitmapHandle.SetBitmap(bmp)
            bitmapHandle.Center()
            bitmapHandle.Refresh()
        else:
            return bmp
Ejemplo n.º 17
0
    def Update(self, bitmapHandle=None, listing=None):
        """ Updates the Labelled Image using the current parameters and
            Listing is a tuple that provides the imlist handle and index"""

        bmp = Conversions.piltoimage(self.thumbX.copy()).ConvertToBitmap()
        bmp = TEXT.write(self.dateText, bmp, self.align, self.font,
                         self.fontcolor, self.position)

        if (bitmapHandle):
            bitmapHandle.SetBitmap(bmp)
            bitmapHandle.Center()
            bitmapHandle.Refresh()
        else:
            return bmp
Ejemplo n.º 18
0
def getCurrentTemp(lat, lng):
    """Returns the current temperature (int) of the location
        -inputs: lat - type:double, lng - type:double
    >>> ct = getCurrentTemp(47.53,-122.03)
    >>> ct == None
    False
    """
    url = address + str(lat) + "&lon=" + str(lng)
    json_data = requests.get(url).json()
    currentTemp = json_data['main']['temp']
    currentFTemp = CNVRT.kelvinToFarenheit(currentTemp)
    #print()
    #print(currentFTemp)
    return int(currentFTemp)
Ejemplo n.º 19
0
def getCurrentWeatherandTemp(lat, lng):
    """Returns the current temperature(int) and weather(string) of the location
        -inputs: lat - type:double, lng - type:double
    >>> cwt = getCurrentWeatherandTemp(47.53,-122.03)
    >>> cwt == (None, None)
    False
    """
    url = address + str(lat) + "&lon=" + str(lng)
    json_data = requests.get(url).json()
    currentTemp = json_data['main']['temp']
    #print("CURRENT TEMP: ", currentTemp)
    #KELVIN TEMP IS CORRECT SOMETHING ABOUT THE CONVERSION IS NOW OFF
    currentFTemp = CNVRT.kelvinToFarenheit(currentTemp)
    currentWeather = json_data['weather'][0]['main']
    return (currentWeather, currentFTemp)
def mixcolumn(datalist):
    # according to the block length we do 2, 4 or 8 times the mix
    datalistmix = []
    for i in range(0, len(datalist) - 1, 2):
        m11 = Arithmod.add_64bits(Conversions.int2bin_str(datalist[i]), Conversions.int2bin_str(datalist[i + 1]))
        m11 = Conversions.bin_str2int(m11)

        rotation = Util.rotate_right(Conversions.int2bin_str(datalist[(i + 1)]), R)

        m22 = Arithmod.xor_bin_str(Conversions.int2bin_str(m11), Conversions.int2bin_str(rotation))
        m22 = Conversions.bin_str2int(m22)
        datalistmix.append(m11)
        datalistmix.append(m22)
    return datalistmix
Ejemplo n.º 21
0
def readFile(trainingdatafile, trainingtargetfile, testingdatafile,
             testingtargetfile, num_features):
    training_features = []
    training_targets = []
    testing_features = []
    testing_targets = []

    trainingdatafilep = open(trainingdatafile, 'r')
    for line in trainingdatafilep:
        if line.strip():
            exampleString = [
                number for number in line.split("\t") if number is not ""
            ]
            example = []
            for exampleStringUnit in exampleString:
                example.append(float(exampleStringUnit))
            assert len(example) == num_features
            training_features.append(example)
    trainingdatafilep.close()

    trainingtargetfilep = open(trainingtargetfile, 'r')
    for line in trainingtargetfilep:
        if line.strip():
            training_targets.append(int(line))
    trainingtargetfilep.close()
    training_targets = Conversions.convertIntsToArrs(training_targets)

    testingdatafilep = open(testingdatafile, 'r')
    for line in testingdatafilep:
        if line.strip():
            exampleString = [
                number for number in line.split("\t") if number is not ""
            ]
            example = []
            for exampleStringUnit in exampleString:
                example.append(float(exampleStringUnit))
            assert len(example) == num_features
            testing_features.append(example)
    testingdatafilep.close()

    testingtargetfilep = open(testingtargetfile, 'r')
    for line in testingtargetfilep:
        if line.strip():
            testing_targets.append(int(line))
    testingtargetfilep.close()
    testing_targets = Conversions.convertIntsToArrs(testing_targets)

    training_features = Conversions.convertListsToArrs(training_features)
    training_targets = Conversions.convertListsToArrs(training_targets)
    testing_features = Conversions.convertListsToArrs(testing_features)
    testing_targets = Conversions.convertListsToArrs(testing_targets)
    return training_features, training_targets, testing_features, testing_targets
Ejemplo n.º 22
0
    def look(self, board):
        """ Populates:
            self.check_vision
            self.avail_moves
            self.avail_captures
            self.supporting
        """
        self.clear_vision()
        # According to movement rules..
        for i, j in self.pattern:
            new_row = self.location[0] + i
            new_col = self.location[1] + j

            # ..and for as far as they can see..
            for _ in range(self.steps):
                # if the square is on the board..
                if not Conversions.legal(new_row, new_col):
                    break
                self.check_vision.add(
                    (new_row, new_col))  # ..add coord to .check_vision
                square = board.squares[new_row][new_col]
                # ..and if square is empty..
                if square.__class__.__name__ == 'Empty':
                    self.avail_moves.add(
                        (new_row, new_col))  # add coord to .avail_moves
                    new_row += i  # and increment for next square
                    new_col += j  # and increment for next square
                # if it's an opposition piece..
                elif square.colour != self.colour:
                    self.avail_captures.add(
                        (new_row, new_col))  # ..add coord to .avail_captures
                    break
                # if it's an allied piece..
                else:
                    self.supporting.add(
                        (new_row, new_col))  # ..add coord to .supporting
                    break
Ejemplo n.º 23
0
def Main():
    test = GetProgram()
    
    if test == ('ReduceFraction'):
        ReduceFraction.Main()
        
    elif test == ('DivisibleBy'):
        num = int( input("What number are you testing: ") )
        print ( DivisibleBy.Main(num) )
        
    elif test == ('FactorQuadraticsAddition'):
        FactorQuadraticsAddition.Main()

    elif test == ('Conversions'):
        Conversions.Main()

    elif test == ('GCF'):
        a = int( input("First number: ") )
        b = int( input("Second number: ") )
        print ( GCF.Main(a, b) )
        
    else:
        print ("Unknown directory")
        Main()
Ejemplo n.º 24
0
def apply(x):
    if x < 3:
        mode = 0
        while mode != 1 and mode != 2:
            mode = int(
                input("Mode de (dé)chiffrement : \n\t1. ECB\n\t2. CBC\n"))
        key_len = 0
        while (key_len != 256) and (key_len != 512) and (key_len != 1024):
            key_len = int(input("Taille de la clé en bits(256/512/1024): "))
        file_key = input("Chemin du fichier de la clé: ")
        passwd_user = input("Mot de passe pour chiffrer la clé: ")
        file_path = input("Chemin du fichier à (dé)chiffrer : ")
        word_len = 64
        num_words = int(key_len / word_len)
        word_len_bytes = int(word_len / 8)

        if x == 1:
            file_data = IO.readfile(file_path, word_len, 1)
            file_data_list = Util.organize_data_list(file_data, num_words)
            encrypted_file = ThreeFish.threefish_chiffrement(
                file_data_list, mode, key_len, passwd_user, file_key)
            IO.write_2D_list(file_path, encrypted_file, word_len_bytes)
            IO.rename_file(file_path, 0)

            print("Chiffrement terminé.")

        elif x == 2:
            ciph_data = IO.readfile(file_path, word_len, 0)
            ciph_data_list = Util.organize_data_list(ciph_data, num_words)
            clear_file_data, valeur_pad = ThreeFish.threefish_dechiffrement(
                ciph_data_list, mode, key_len, word_len, passwd_user, file_key)
            IO.write_file_list_pad(file_path, clear_file_data, word_len_bytes,
                                   valeur_pad)
            IO.rename_file(file_path, 1)

            print("Déchiffrement terminé.")

    elif x == 3:
        filepath = input("Chemin du fichier à chiffrer:")
        file_data = IO.read_bytes(filepath)
        ans = ''
        while ans != 'y' and ans != 'n' and ans != 'Y' and ans != 'N':
            ans = input("Avez-vous un fichier de clé publique ? (y/n) ")
        if ans == 'y' or ans == 'Y':
            keypath = input("Chemin de la clé publique: ")
            ciph_data = CramerShoup.encode_with_key(file_data, keypath)
        else:
            k = int(input("Taille de clé souhaitée en bits: "))
            password = input("Mot de passe pour chiffrer la clé privée: ")
            keypath = input("Chemin du répertoire des clés: ")
            ciph_data = CramerShoup.encode_no_key(file_data, keypath, k,
                                                  password)

        ciph_bytes = Conversions.int_list2bytes(ciph_data, 8)
        IO.write_bytes(filepath, ciph_bytes)
        IO.rename_file(filepath, 0)

        print("Chiffrement terminé.")

    elif x == 4:
        filepath = input("Chemin du fichier à déchiffrer: ")
        file_data = IO.read_bytes(filepath)
        keypath = input("Chemin de la clé privée: ")
        password = input("Mot de passe: ")

        ciph_data = Conversions.bytes2int_list(file_data, 8)
        clear_data = CramerShoup.decode(ciph_data, keypath, password)
        IO.write_bytes(filepath, clear_data)
        IO.rename_file(filepath, 1)

        print("Déchiffrement terminé.")

    elif x == 5:
        hash_len = 0
        while hash_len != 256 and hash_len != 512 and hash_len != 1 and hash_len != 2:
            hash_len = int(input("1. BLAKE-256\n2. BLAKE-512\n"))
        if hash_len < 256:
            hash_len *= 32
        else:
            hash_len //= 8

        filepath = input("Chemin du fichier: ")
        with open(filepath, 'r') as rfile:
            file_data = rfile.read()

        ans = ''
        while ans != 'y' and ans != 'n' and ans != 'Y' and ans != 'N':
            ans = input("Protéger l'empreinte ? (y/n) ")

        key = ''
        if ans == 'y' or ans == 'Y':
            key = input("Mot de passe: ")

        h = hex(Hash.blake_hash(file_data, hash_len, key)) + '\n'

        # Rename file : "name.ext" -> "name~hash.ext"
        path = filepath.split('/')
        last = len(path) - 1
        filename = path[last].split('.')
        filename[0] += '~hash'
        path[last] = '.'.join(filename)
        filepath = '/'.join(path)

        with open(filepath, 'w') as wfile:
            wfile.write(h)

    elif x == 6:
        hash_len = 0
        while hash_len != 256 and hash_len != 512 and hash_len != 1 and hash_len != 2:
            hash_len = int(input("1. BLAKE-256\n2. BLAKE-512\n"))
        if hash_len < 256:
            hash_len *= 32
        else:
            hash_len //= 8

        filepath = input("Chemin du fichier: ")
        with open(filepath, 'r') as rfile:
            file_data = rfile.read()

        hashpath = input("Chemin du hash: ")
        with open(hashpath, 'r') as hfile:
            hash = hfile.read()

        ans = ''
        while ans != 'y' and ans != 'n' and ans != 'Y' and ans != 'N':
            ans = input("Empreinte protégée ?(y/n) ")

        key = ''
        if ans == 'y' or ans == 'Y':
            key = input("Mot de passe: ")

        h = hex(Hash.blake_hash(file_data, hash_len, key)) + '\n'

        if h == hash:
            print("Les empreintes sont égales.")
        else:
            print("Les empreintes ne correspondent pas.")
Ejemplo n.º 25
0
    def look(self, board):
        """ Additionally to parent class:
                - Populates available moves with squares pertaining to legal Castling maneuvers.
                    In these cases the Rook has no knowledge of the potential of Castling and is moved
                    'manually' by the game logic embedded in the Board.move() method.
                - Prevents population of available moves and available captures with moves that
                    would result in the King being in Check.
        """
        self.clear_vision()

        # NORMAL MOVEMENT
        for i, j in self.pattern:
            new_row = self.location[0] + i
            new_col = self.location[1] + j

            # If the square is on the board..
            if not Conversions.legal(new_row, new_col):
                continue
            self.check_vision.add(
                (new_row, new_col))  # ..add coord to .check_vision
            square = board.squares[new_row][new_col]
            # If the coord is empty..
            if square.__class__.__name__ == 'Empty':
                # and is not covered..
                if board.get_pieces(self.opp_colour,
                                    in_check_vision=(new_row, new_col)):
                    continue
                self.avail_moves.add(
                    (new_row, new_col))  # ..add coord to .avail_moves
            # If it's an opposition piece..
            elif square.colour != self.colour:
                # and is not covered..
                if board.get_pieces(self.opp_colour,
                                    in_check_vision=(new_row, new_col)):
                    continue
                self.avail_captures.add(
                    (new_row, new_col))  # ..add coord to their .avail_captures
            # If it's an allied piece..
            else:
                self.supporting.add(
                    (new_row, new_col))  # ..add coord to .supporting

        # CASTLING MOVEMENT
        if not self.has_moved:  # if not yet moved..
            checks, _ = board.get_checks()
            if self.colour not in checks:  # ..and not in check..
                row = self.location[0]
                for _, j in self.castle_pattern:  # look in both directions along the rank
                    new_col = self.location[1] + j
                    for _ in range(4):
                        if Conversions.legal(
                                row, new_col
                        ):  # if the next square is on the board..
                            square = board.squares[row][new_col]  # check it
                            if square.__class__.__name__ == 'Empty':  # if it's empty and not visible to opponent..
                                if board.get_pieces(self.opp_colour,
                                                    in_check_vision=square.
                                                    location) is not None:
                                    new_col += j  # keep going
                                    continue
                            elif square.__class__.__name__ == 'Rook':  # if it's a rook and it's not moved..
                                if not square.has_moved:
                                    castle_location = (row, self.location[1] +
                                                       j * 2)
                                    self.avail_moves.add(
                                        castle_location
                                    )  # ..then castling is legal
                            else:  # otherwise: no castling on this side
                                break
                        else:  # then we are off the board
                            break
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from random import getrandbits
import Arithmod, Conversions, Keys, IO, Util

# Constants
tweak0 = Conversions.str2int("cogranne")
tweak1 = Conversions.str2int("gs15love")
tweak2 = tweak0 ^ tweak1
tweaks = [tweak0, tweak1, tweak2]
C = 0x1bd11bdaa9fc1a22
R = 49


# Is apply when the user chose the option 1 in the menu which is correspond to ThreeFish cipher
# input :
#   file_data_list = 2D array of int
#   mode = int, permit to choose between ecb or cbc decipher
#   key_len = int, length of the key, 256, 512 or 1024
# output = 2D array of int, correspond to the cipher data
def threefish_chiffrement(file_data_list, mode, key_len, passwd_user, file_key):
    key, keyuser = keygen(key_len)
    tab_key = keygenturn(key)
    # cipher the key using the password given by the user
    cipher_key = Keys.cipher_key(passwd_user, key)
    # writing cipher key in the specific file
    IO.write_2D_list(file_key, cipher_key, 8)

    Keys.print_key(key_len, keyuser)
def AddMagneticCoordinates(sourceFilename, resultFilename):
    startSecs = time.time()
    prev_time = current_time = None
    timestep = 0
    linenum = 0
    CSVfileOUT = open(resultFilename, 'w')
    CSVwriter = csv.writer(CSVfileOUT, delimiter=',')
    CSVwriter.writerow([
        "Epoch(UTCG)", "Lat_GEOD(deg)", "Lon_GEOD(deg)", "Height_WGS84 (km)",
        "Daedalus.Magnetic Latitude", "Daedalus.Magnetic Longitude",
        "Daedalus.MLT"
    ])
    with open(sourceFilename) as CSVfileIN:
        CSVreader = csv.reader(CSVfileIN)
        # locate the column numnbers of interest inside the csv file
        CSVheader = next(CSVreader)
        Time_idx = CSVheader.index(
            "Epoch(UTCG)")  #CSVheader.index( "Daedalus.EpochText" )
        Lat_idx = CSVheader.index(
            "Lat_GEOD(deg)")  #CSVheader.index( "Daedalus.Latitude" )
        Lon_idx = CSVheader.index(
            "Lon_GEOD(deg)")  #CSVheader.index( "Daedalus.Longitude" )
        Alt_idx = CSVheader.index(
            "Height_WGS84 (km)")  #CSVheader.index( "Daedalus.Longitude" )
        # read the orbit file
        for row in CSVreader:  # for each satellite position
            if len(list(row)) == 0: break  # <<<<
            linenum += 1
            resultItems = list()
            # add the standard fields to the result file
            resultItems.append(row[Time_idx])
            resultItems.append(
                row[Lat_idx])  # Latitude is geodetic inside the orbit file
            resultItems.append(row[Lon_idx])
            resultItems.append(row[Alt_idx])
            # Calculate the extra fields
            prev_time = current_time
            current_time = parseDaedalusDate(
                row[Time_idx])  # read time for the current orbit position
            if current_time == None:
                print("ERROR - Wrong time format at line", linenum, ":",
                      row[Time_idx])
                continue
            if prev_time is not None:
                if timestep == 0:
                    timestep = calendar.timegm(
                        current_time.utctimetuple()) - calendar.timegm(
                            prev_time.utctimetuple())
                else:
                    if calendar.timegm(
                            current_time.utctimetuple()) - calendar.timegm(
                                prev_time.utctimetuple()) != timestep:
                        print(
                            "Time leap at line", linenum, ":", row, "(",
                            calendar.timegm(current_time.utctimetuple()) -
                            calendar.timegm(prev_time.utctimetuple()), "sec)",
                            "\n", prev_time, "\n", current_time)
            # take care of time so that it is compatible with igrf
            #if current_time.year > 2024:
            #    time_for_igrf = current_time - relativedelta(years=13)
            #else:
            #    time_for_igrf = current_time
            time_for_igrf = current_time
            MagneticLatitude, MagneticLongitude, MagneticLocalTime = Conversions.getMagneticProperties(
                time_for_igrf, float(row[Lat_idx]), float(row[Lon_idx]),
                float(row[Alt_idx]))
            # add the extra fields to the result file
            resultItems.append(MagneticLatitude)
            resultItems.append(MagneticLongitude)
            resultItems.append(MagneticLocalTime)
            # write it
            CSVwriter.writerow(resultItems)
    # clean up
    CSVfileOUT.close()
    finishSecs = time.time()
    print("Processed", linenum, "lines in", finishSecs - startSecs, "sec")
Ejemplo n.º 28
0
    def loop():
        convert = input("Would you like to make a conversion? y/n: ")
        while convert == "y":
            conversion = input("""You can choose from 6 conversions:
Decimal to Binary (type: DTB)
Binary to Decimal (type: BTD)
Decimal to Hexidecimal (type: DTH)
Hexidecimal to Decimal (type: HTD)
Binary to Hexidecimal (type: BTH)
Hexidecimal to Binary (type: HTB)

Which do you choose?

: """)
            if conversion == "DTB":
                C.dtb()
                convert = input("Make another conversion? y/n: ")
            if conversion == "BTD":
                C.btd()
                convert = input("Make another conversion? y/n: ")
            if conversion == "DTH":
                C.dth()
                convert = input("Make another conversion? y/n: ")
            if conversion == "HTD":
                C.htd()
                convert = input("Make another conversion? y/n: ")
            if conversion == "BTH":
                C.bth()
                convert = input("Make another conversion? y/n: ")
            if conversion == "HTB":
                C.htb()
                convert = input("Make another conversion? y/n: ")
Ejemplo n.º 29
0
def plot_surface_map(ncFile,
                     targetDir,
                     withTemperature=True,
                     withWinds=True,
                     windScaleFactor=50,
                     withMSLP=True):
    logger = PyPostTools.pyPostLogger()
    if (withTemperature == False and withWinds == False and withMSLP == False):
        logger.write("Error in plot_surface_map(): Nothing to do.")
        return False
    fig, ax, X, Y = prepare_plot_object(ncFile)
    st, fh, fh_int = getTimeObjects(ncFile)

    titleAdd = ""
    if (withTemperature):
        T = ncFile["SFC_T"]
        TF = Conversions.K_to_F(T)
        clevs = np.arange(-30, 115, 5)
        contours = plt.contourf(X,
                                Y,
                                TF,
                                clevs,
                                cmap=ColorMaps.temp_colormap,
                                transform=ccrs.PlateCarree())
        cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
        cbar.set_label("Temperature (F)")
        titleAdd += "Temperature "

    if (withMSLP):
        SLP = to_np(ncFile["MSLP"])
        smooth_slp = gaussian_filter(SLP, sigma=3)
        levs = np.arange(950, 1050, 4)
        linesC = plt.contour(X,
                             Y,
                             smooth_slp,
                             levs,
                             colors="black",
                             transform=ccrs.PlateCarree(),
                             linewidths=1)
        plt.clabel(linesC, inline=1, fontsize=10, fmt="%i")
        titleAdd += "MSLP (mb) "

    if (withWinds):
        u = ncFile["SFC_U"]
        v = ncFile["SFC_V"]

        uKT = Conversions.ms_to_kts(u)
        vKT = Conversions.ms_to_kts(v)
        plt.barbs(to_np(X[::windScaleFactor, ::windScaleFactor]),
                  to_np(Y[::windScaleFactor, ::windScaleFactor]),
                  to_np(uKT[::windScaleFactor, ::windScaleFactor]),
                  to_np(vKT[::windScaleFactor, ::windScaleFactor]),
                  transform=ccrs.PlateCarree(),
                  length=6)
        titleAdd += "Winds "
    # Finish things up, for the title crop off the extra comma at the end, add the time text, and save.
    titleAdd = titleAdd.replace(" ", ", ")
    titleAdd = titleAdd[:-2]
    plt.title("Surface Map (" + titleAdd + ")")
    plt.text(0.02,
             -0.02,
             "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.text(0.7,
             -0.02,
             "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
             ha='left',
             va='center',
             transform=ax.transAxes)
    plt.subplots_adjust(bottom=0.1)
    plt.savefig(targetDir + "/sfcmap_F" + str(fh_int))
    plt.close(fig)
    return True
Ejemplo n.º 30
0
def plot_theta_e(ncFile,
                 targetDir,
                 levels,
                 withHeights=True,
                 withWinds=True,
                 windScaleFactor=50):
    logger = PyPostTools.pyPostLogger()
    st, fh, fh_int = getTimeObjects(ncFile)

    for level in levels:
        fig, ax, X, Y = prepare_plot_object(ncFile)
        titleAdd = ""
        clevs = np.arange(240, 380, 5)

        if (level == 0):
            # Surface is special in regards to naming and ignoring geo.hgt. argument
            eth = ncFile["SFC_THETA_E"]
            contours = plt.contourf(X,
                                    Y,
                                    eth,
                                    clevs,
                                    cmap=get_cmap('gist_ncar'),
                                    transform=ccrs.PlateCarree())
            cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
            cbar.set_label("Equivalent Potential Temperature (K)")

            if (withWinds):
                u = ncFile["SFC_U"]
                v = ncFile["SFC_V"]
                uKT = Conversions.ms_to_kts(u)
                vKT = Conversions.ms_to_kts(v)

                plt.barbs(to_np(X[::windScaleFactor, ::windScaleFactor]),
                          to_np(Y[::windScaleFactor, ::windScaleFactor]),
                          to_np(uKT[::windScaleFactor, ::windScaleFactor]),
                          to_np(vKT[::windScaleFactor, ::windScaleFactor]),
                          transform=ccrs.PlateCarree(),
                          length=6)

                titleAdd += ", Winds (Kts)"
            plt.title("Surface Theta-E (K)" + titleAdd)
            plt.text(0.02,
                     -0.02,
                     "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
                     ha='left',
                     va='center',
                     transform=ax.transAxes)
            plt.text(0.7,
                     -0.02,
                     "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
                     ha='left',
                     va='center',
                     transform=ax.transAxes)
            plt.subplots_adjust(bottom=0.1)
            plt.savefig(targetDir + "/ThetaE_SFC_F" + str(fh_int))
            plt.close(fig)
        else:
            eth = ncFile["THETA_E_" + str(level)]
            contours = plt.contourf(X,
                                    Y,
                                    eth,
                                    clevs,
                                    cmap=get_cmap('gist_ncar'),
                                    transform=ccrs.PlateCarree())
            cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
            cbar.set_label("Equivalent Potential Temperature (K)")

            if (withHeights == True):
                z = ncFile["GEOHT_" + str(level)]
                zDM = z / 10

                smooth_lines = gaussian_filter(to_np(zDM), sigma=3)

                if (level <= 200):
                    cont_levels = np.arange(800., 1600., 6.)
                elif (level <= 400):
                    cont_levels = np.arange(600., 1200., 6.)
                elif (level <= 600):
                    cont_levels = np.arange(200., 800., 6.)
                elif (level <= 800):
                    cont_levels = np.arange(100., 600., 6.)
                else:
                    cont_levels = np.arange(0., 400., 6.)

                contours = plt.contour(X,
                                       Y,
                                       smooth_lines,
                                       levels=cont_levels,
                                       colors="black",
                                       transform=ccrs.PlateCarree())
                plt.clabel(contours, inline=1, fontsize=10, fmt="%i")

                titleAdd += ", Geopotential Height (dm)"

            if (withWinds):
                u = ncFile["U_" + str(level)]
                v = ncFile["V_" + str(level)]
                uKT = Conversions.ms_to_kts(u)
                vKT = Conversions.ms_to_kts(v)

                plt.barbs(to_np(X[::windScaleFactor, ::windScaleFactor]),
                          to_np(Y[::windScaleFactor, ::windScaleFactor]),
                          to_np(uKT[::windScaleFactor, ::windScaleFactor]),
                          to_np(vKT[::windScaleFactor, ::windScaleFactor]),
                          transform=ccrs.PlateCarree(),
                          length=6)

                titleAdd += ", Winds (Kts)"
            plt.title(str(level) + "mb Theta-E (K)" + titleAdd)
            plt.text(0.02,
                     -0.02,
                     "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
                     ha='left',
                     va='center',
                     transform=ax.transAxes)
            plt.text(0.7,
                     -0.02,
                     "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
                     ha='left',
                     va='center',
                     transform=ax.transAxes)
            plt.subplots_adjust(bottom=0.1)
            plt.savefig(targetDir + "/ThetaE_" + str(level) + "_F" +
                        str(fh_int))
            plt.close(fig)
Ejemplo n.º 31
0
def plot_upper_lv_winds(ncFile,
                        targetDir,
                        levels,
                        windScaleFactor=50,
                        withHeights=True):
    logger = PyPostTools.pyPostLogger()
    st, fh, fh_int = getTimeObjects(ncFile)

    for level in levels:
        fig, ax, X, Y = prepare_plot_object(ncFile)

        titleAdd = ""

        u = ncFile["U_" + str(level)]
        v = ncFile["V_" + str(level)]

        uKT = Conversions.ms_to_kts(u)
        vKT = Conversions.ms_to_kts(v)

        spd = np.sqrt(uKT * uKT + vKT * vKT)
        smooth_wnd = gaussian_filter(to_np(spd), sigma=3)

        if level >= 850:
            clevs = np.arange(10, 120, 5)
        elif (level >= 500 and level < 850):
            clevs = np.arange(25, 180, 5)
        else:
            clevs = np.arange(50, 230, 5)

        contours = plt.contourf(X,
                                Y,
                                smooth_wnd,
                                clevs,
                                cmap=get_cmap('rainbow'),
                                transform=ccrs.PlateCarree())
        cbar = plt.colorbar(ax=ax, orientation="horizontal", pad=.05)
        cbar.set_label("Wind Speed (Kts)")

        plt.barbs(to_np(X[::windScaleFactor, ::windScaleFactor]),
                  to_np(Y[::windScaleFactor, ::windScaleFactor]),
                  to_np(uKT[::windScaleFactor, ::windScaleFactor]),
                  to_np(vKT[::windScaleFactor, ::windScaleFactor]),
                  transform=ccrs.PlateCarree(),
                  length=6)

        if (withHeights == True):
            z = ncFile["GEOHT_" + str(level)]
            zDM = z / 10

            smooth_lines = gaussian_filter(to_np(zDM), sigma=3)

            if (level <= 200):
                cont_levels = np.arange(800., 1600., 6.)
            elif (level <= 400):
                cont_levels = np.arange(600., 1200., 6.)
            elif (level <= 600):
                cont_levels = np.arange(200., 800., 6.)
            elif (level <= 800):
                cont_levels = np.arange(100., 600., 6.)
            else:
                cont_levels = np.arange(0., 400., 6.)

            contours = plt.contour(X,
                                   Y,
                                   smooth_lines,
                                   levels=cont_levels,
                                   colors="black",
                                   transform=ccrs.PlateCarree())
            plt.clabel(contours, inline=1, fontsize=10, fmt="%i")

            titleAdd += ", Geopotential Height (dm)"

        plt.title(str(level) + "mb Winds (kts)" + titleAdd)
        plt.text(0.02,
                 -0.02,
                 "Forecast Time: " + fh.strftime("%Y-%m-%d %H:%M UTC"),
                 ha='left',
                 va='center',
                 transform=ax.transAxes)
        plt.text(0.7,
                 -0.02,
                 "Initialized: " + st.strftime("%Y-%m-%d %H:%M UTC"),
                 ha='left',
                 va='center',
                 transform=ax.transAxes)
        plt.subplots_adjust(bottom=0.1)
        plt.savefig(targetDir + "/" + str(level) + "winds_F" + str(fh_int))
        plt.close(fig)
Ejemplo n.º 32
0
def main():
    if len(sys.argv) != 5:
        print "<python Init.py TrainingData.txt TrainingTarget.txt TestingData.txt TestingTarget.txt>"
        sys.exit()

    if not os.path.isfile(sys.argv[1]) or not os.path.isfile(
            sys.argv[2]) or not os.path.isfile(
                sys.argv[3]) or not os.path.isfile(sys.argv[4]):
        print "File does not exist"
        print "<python Init.py TrainingData.txt TrainingTarget.txt TestingData.txt TestingTarget.txt>"
        sys.exit()

    #calculating number of features
    firstline = open(sys.argv[1]).readline()
    first_example = [
        numbers for numbers in firstline.split("\t") if numbers is not ""
    ]
    if len(first_example) < 1:
        print "There must be more than one feature in the data."
    else:
        num_features = len(first_example)
    #reading from training file
    training_features, training_targets, testing_features, testing_targets = FileReader.readFile(
        sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], num_features)
    assert len(training_features) == len(training_targets)
    assert len(testing_features) == len(testing_targets)
    learning_rate = float(raw_input("What is the learning rate? "))
    assert learning_rate > 0 and learning_rate < 1
    num_iterations = input("How many iterations? ")
    assert num_iterations > 0
    numHidLayers = input("How many HIDDEN LAYERS? ")
    assert isinstance(numHidLayers, int)
    numNeuronsInLayer = num_features
    numNeuronsOutLayer = len(testing_targets[0])
    numNeuronsHidLayers = []
    for i in range(0, numHidLayers):
        numNeuronsHidLayers.append(
            input("How many Neurons Hidden Layer " + str(i + 1) + " : "))
        assert isinstance(numNeuronsHidLayers[i], int)
    tic = time.time()
    numNeurons = []
    numNeurons.append(numNeuronsInLayer)
    numNeurons.extend(numNeuronsHidLayers)
    numNeurons.append(numNeuronsOutLayer)
    allWeights = PerceptronLearning.initializeWeights(numNeurons)
    allBiases = PerceptronLearning.initializeBiases(numNeurons)

    for i in range(0, num_iterations):
        predicted_targets = []
        for j in range(0, len(training_features)):
            allOutputs = PerceptronLearning.forwardProp(
                training_features[j], allWeights, allBiases)
            predicted_targets.append(allOutputs[-1])
            allDeltas = PerceptronLearning.backwardProp(
                training_targets[j], predicted_targets[j], allWeights)
            allBiases = PerceptronLearning.updateBiases(
                allDeltas, allBiases, learning_rate, len(training_features))
            allWeights = PerceptronLearning.updateWeights(
                allOutputs, allDeltas, allWeights, learning_rate,
                len(training_features))
        if i % 100 == 99:
            error = PerceptronLearning.calculateError(training_targets,
                                                      predicted_targets)
            print "Error at iteration", i, "is", np.squeeze(error)

    predicted_test_targets_arrs = []
    for i in range(0, len(testing_features)):
        allOutputs = PerceptronLearning.forwardProp(testing_features[i],
                                                    allWeights, allBiases)
        predicted_test_targets_arrs.append(allOutputs[-1])
    testing_targets = Conversions.convertArrsToInts(testing_targets)
    predicted_test_targets = Conversions.convertArrsToInts(
        predicted_test_targets_arrs)
    # print "original"
    # print testing_targets
    # print "predicted"
    # print predicted_test_targets

    assert len(testing_targets) == len(predicted_test_targets)
    correct = 0
    total = 0
    for i in range(0, len(testing_targets)):
        total += 1
        if testing_targets[i] == predicted_test_targets[i]:
            correct += 1
    print "The accuracy is", correct / float(total)
    toc = time.time()
    print "Running Time :", (toc - tic)
    return 0
Ejemplo n.º 33
0
def run():

    # These have to be in meters
    total_radius = Decimal(30)
    outer_radius = Decimal(4)
    wall_thickness = Decimal(.0254 * 1)

    # m/s2
    acceleration = Decimal(9.81)

    # Must be in kilograms
    additional_mass = Decimal(100000)

    # Put in terms of g/cm3
    density_of_material = Decimal(2.84)  # g/cm3 Al alloy 2219
    density_of_material = Decimal(
        Conversions.g_cm3_to_kg_m3(density_of_material))

    # Max tensile strength of the material given in MPa
    tensile_strength = Decimal(248)

    if wall_thickness > outer_radius:
        print(
            "Wall thickness cannot be bigger than the outer radius and will be clamped to that number"
        )
        wall_thickness = outer_radius

    # Find a lot of common variables which are used often in other equations
    linear_velocity = Formulas.linear_speed_rotational(total_radius,
                                                       acceleration)
    rpm = Conversions.linear_to_rpm(total_radius, linear_velocity)
    volume_of_walls = Formulas.volume_of_torus_wall(total_radius, outer_radius,
                                                    wall_thickness)

    # Calculate the stress on the torus in MPa
    stress = Formulas.stress_on_torus(total_radius, outer_radius,
                                      wall_thickness, density_of_material,
                                      acceleration, additional_mass)

    # Volume of torus wall
    print('Volume of torus wall(internal): ' +
          str(round(volume_of_walls, pretty_round)) +
          ' m3'.translate(superscript))

    # Internal volume of torus for thickness of wall
    print('Volume of torus (hollow): ' + str(
        round(
            Formulas.volume_of_hollow_torus(total_radius, outer_radius,
                                            wall_thickness), pretty_round)) +
          ' m3'.translate(superscript))

    # Speed torus would have to spin linearly to achieve centripetal acceleration
    print('Linear speed: ' + str(round(linear_velocity, pretty_round)) +
          ' m/s'.translate(superscript))

    # 2-3 rpm is optimal, 10 rpm max can be trained
    print('RPM: ' + str(
        round(Conversions.linear_to_rpm(total_radius, linear_velocity),
              pretty_round)) + ' rpm')

    # Outer circumference of torus
    print('Outer circumference: ' + str(
        round(Formulas.circumference_of_circle(total_radius), pretty_round)) +
          ' m')

    # Cross section used to calculate force acting on torus
    print('Cross Section of torus: ' + str(
        round(
            Formulas.cross_section_hollow_torus(outer_radius, wall_thickness),
            pretty_round)) + ' m2'.translate(superscript))

    # Convert to imperial so it's easier to read
    print('Internal radius of torus: ' + str(
        round(Conversions.meter_to_feet(outer_radius -
                                        wall_thickness), pretty_round)) +
          ' ft')

    # Useful when performing other calculations
    print('Angular Velocity: ' +
          str(round(Conversions.rpm_to_angular(rpm), pretty_round)) + ' rad/s')

    # Give others an idea how big torus would be
    print('Stories high: ' +
          str(round((total_radius * Decimal(2)) / Decimal(ft_per_story))) +
          ' (' + str(ft_per_story) + ' ft per story)'.translate(superscript))
    # Mass of ring
    print('Mass: ' +
          str(round(density_of_material * volume_of_walls +
                    additional_mass, 2)) + ' kg')

    print('---------------------')
    # Force along cross sectional area in MPa
    print('Force on torus: ' + str(round(stress, 2)) + ' MPa')

    if stress <= tensile_strength:
        print("The torus can hold itself with: " +
              str(round(tensile_strength - stress, 2)) + ' MPa remaining (' +
              str(100 * (1 - round(
                  (tensile_strength - stress) / tensile_strength, 2))) +
              "% of total applicable)")
    else:
        print("The torus can't hold itself with: " +
              str(round(tensile_strength - stress, 2)) + ' MPa in excess (' +
              str(100 * (1 - round(
                  (tensile_strength - stress) / tensile_strength, 2))) +
              "% of total applicable)")

    if draw:
        Drawing.draw_torus(total_radius,
                           outer_radius,
                           kind=GraphType.MPL,
                           z_ratio=0)