def chordGen(): bones = chord_structures[randint(0, len(chord_structures)-1)] chords = [] for root in bones: offset = randint(-1, 1) * 0 c = Chord(root+offset) c.setDuration(4) chords.append(c) return chords
def makegraph(self, outfile, masterkey="stats", key="occurences"): """ Generate a graph. @param outfile: path to file to write to @type outfile: L{str} @param masterkey: category key of get_pairing_data()'s result to use. @type masterkey: L{str} @param key: key for value to use @type key: L{str} """ # prepare data data = self.get_pairing_data() pairingstats = data[masterkey] # purge all entries were value of key <= 0 to_purge = set() for pairing in pairingstats.keys(): v = pairingstats[pairing][key] if v <= 0: to_purge.add(pairing) for p in to_purge: del pairingstats[p] names = list( sorted( set([name for pairing in data[masterkey] for name in pairing]))) n_names = len(names) matrix = [[0] * n_names for i in range(n_names)] for pairing in pairingstats.keys(): v = pairingstats[pairing][key] name_1, name_2 = pairing i, j = names.index(name_1), names.index(name_2) matrix[i][j] = v matrix[j][i] = v c = Chord( matrix, names, width=1600, margin=200, padding=0.02, wrap_labels=False, font_size="12px", noun="FanFics", allow_download=True, #title="Ships (by {})".format(key), credit=False, ) c.to_html(filename=outfile)
def __init__(self, tuning_type='equal', initial_duration=1, initial_root_tonality_frequency=440): self.duration = initial_duration self.set_root_tonality_frequency(initial_root_tonality_frequency) self.scale = Scale().get_ratios(tuning_type) intervals = [0 for i in range(5)] self.synths = [ self.synthesize(freq=(self.root_tonality_frequency * interval)) for interval in intervals ] self.set_envelope(self.duration) self.chord_generator = Chord(self.scale, self.root_tonality_frequency)
def closestChord(allFrets, bestChords, allChords): # this method is basically a rough adaptation of # how I remembered the shorest path algorithm. # Each level of recursion that a chord goes down # adds another note to it. If best chords have # 5 chords in it then the best 5 chords have been made, # so exit and if allchords is empty then # all combinations have been tried to exit if ((len(bestChords) == 5) or (len(allChords) == 0)): return # get the chord with the lowest score from heap chord = heapq.heappop(allChords) # if the chord holds all of the notes in it then it is finished if (len(allFrets) <= chord.numNotes): # this for loop sees if the finished # chord is a duplicate, if so move on for x in range(0, len(bestChords)): if chord.__eq__(bestChords[x]): # continue recursion closestChord(allFrets, bestChords, allChords) return # tail recursion bestChords.append(chord) # add the finished chord to the list closestChord(allFrets, bestChords, allChords) # continue recursion return # tail recursion numNotes = chord.numNotes # finds which note the chord is on # the loop gets the frets of the next note to be for y in range(0, len(allFrets[numNotes])): # makes sure that the string that the fret is on is not in use if (chord.frets[allFrets[numNotes][y].string] is None): # this makes sure the note being added # is not lower than the bass note if (chord.bass <= allFrets[numNotes][y].note.numValue): # add fret to chord chord.frets[allFrets[numNotes] [y].string] = allFrets[numNotes][y] # create a new chord to add the new fret onto tempChord = Chord(chord.frets) tempChord.bass = chord.bass # set the bass note of new chord # creates a new chord using the base chord's notes so that # the base chord can be altered without altering the new chord # Push it onto the heap heapq.heappush(allChords, tempChord) # remove the fret from the base chord so that other # frets on the note can be added to the chord chord.frets[allFrets[numNotes][y].string] = None closestChord(allFrets, bestChords, allChords) # continue recursion return # tail recursion
def chordDiagram(request): df_enron = filterDataByTime(request ,pd.read_csv(request.FILES['csv_data'])) names = ['Managing Director', 'In House Lawyer', 'Vice President', 'Employee', 'Unknown', 'Manager', 'Director', 'Trader', 'CEO', 'President'] df_chord = df_enron.groupby(['fromJobtitle', 'toJobtitle'])['date'].count() df_chord = df_chord.unstack().fillna(0).astype(int) df_chord = df_chord.reindex(names) df_chord = df_chord[names] matrix = df_chord.values.tolist() print(Chord(matrix, names, wrap_labels=False)) return HttpResponse(Chord(matrix, names, wrap_labels=False).to_html())
def chordCreate(notes, tuning, numFrets, targetFret, low, high, fretsOnStrings, isBass): app.logger.debug('in chordCreate') # list that will hold all of the possible frets that # can be played with the given notes allFrets = [] for note in notes: # returns the frets that each note can be played on frets = getFrets(note, tuning, numFrets, targetFret, low, high) frets = sortStuff(frets) # sort the frets by distance to the target for fret in frets: # makes sure not to add duplicate frets # if the user say has two of the same note if fret not in fretsOnStrings[fret.string]: # this will store all of the frets that # can be played on each string for the ui fretsOnStrings[fret.string].append(fret) allFrets.append(frets) strings = [None] * 6 # create a 6 unit long list full of None baseChord = Chord(strings) # This is a chord with no notes in it bestChords = [] # stores the five best chords allChords = [] # stores all of the chords that get created in method # creates chords that each hold only one fret of the first note if (len(allFrets) > 0): for fret in allFrets[0]: # get each possible fret of the first note # add the fret of the first note to the baseChord baseChord.frets[fret.string] = fret # create a new chord with the strings tempChord = Chord(baseChord.frets) if (bool(isBass)): # if the user wants to use a bass note this will set it, # it is intialized to 0 otherwise tempChord.bass = fret.note.numValue heapq.heappush(allChords, tempChord) # heap push it to allChords # remove the fret so that the chord is empty again baseChord.frets[fret.string] = None # this is the method that finds the best chords closestChord(allFrets, bestChords, allChords) if len(bestChords) >= 1: # this means at least one chord was found return bestChords # The chord is not possible to make errorStrings = [] for x in range(0, 6): errorStrings.append(Fret(-1, -1, 100, Note(0))) bestChords.append(Chord(errorStrings)) # returns an array holding only one chord with no notes in it return bestChords
def get_chord_type(symbol: str) -> str: orig_symbol = symbol symbol = symbol.replace(' ', '') if symbol == '': return 'no chord' bass: Optional[int] = None seventh: Literal[None, 'min'] = None sixth = False quality: Literal['maj', 'min'] = 'maj' additions = [] inversions = 0 if '/' in symbol: symbol, bass_str = symbol.split('/') bass = identify_note(bass_str) def cut(s): nonlocal symbol if symbol.endswith(s): additions.insert(0, s) symbol = symbol[:-len(s)] return True return False if cut('7b9'): return orig_symbol if cut('7'): seventh = 'min' if cut('6'): sixth = True if cut('m'): quality = 'min' midi = identify_note(symbol) # crash if can't figure it out bass_annotation = '' if bass is not None: try: inversions = [ x % 12 for x in Chord(midi % 12, RelativeChord(quality, seventh)).render() ].index(bass) if inversions: if inversions == 1: ordinal = '1st' elif inversions == 2: ordinal = '2nd' elif inversions == 3: ordinal = '3rd' else: raise Exception('what inversion? {}'.format(inversions)) bass_annotation = ', {} inversion'.format(ordinal) except ValueError: # clean me up manually bass_annotation = ', semitone {} in bass'.format( (bass - midi) % 12) print(orig_symbol) things = [] if quality == 'min': if seventh == 'min': things.append('minor 7th') else: things.append('minor') else: if seventh == 'min': things.append('dominant 7th') else: things.append('major') if sixth: things.append(' sixth') things.append(bass_annotation) return ''.join(things)
def __init__(self): chord = Chord() # this class generates a simulated chord w/ data = chord.final_out() # randomly selected type, key, and inversion self.key = data[2] self.type = data[3] self.inv = data[4] self.input = np.reshape(synth_detect(data[0],44100)[1],(882,1)) # intializes the comparison values for the cost function self.a1 = np.reshape(key_act(self.key + 1)[0][1:],(11,1)) self.a2 = np.reshape(type_act(self.type + 1)[0][1:],(34,1)) self.a3 = np.reshape(inv_act(self.inv + 1)[0][1:],(11,1)) # initializes the wieghts for the network self.w1 = key_weight() self.w2 = type_weight() self.w3 = inv_weight()
def create_chord_diagram(matrix, labels): """ :param matrix: adjacency matrix of weighted usages :param labels: names of all cards :return: chord html file """ from chord import Chord Chord(matrix, labels).to_html()
class PotentialChords(object): """tree containing all potential chords""" BASE_CHORDS = 'C', 'C#', 'Db', 'D', 'D#', 'Eb', 'E', 'F', 'F#', 'Gb', 'G', 'G#', 'Ab', 'A', 'A#', 'Bb', 'B' SPECIAL_CHORDS = 'A/C#', 'A/E', 'A/F', 'A/G', 'A/G#', 'Am/C', 'Am/E', 'Am/F', 'Am/F#', 'Am/G', 'Am/G#', 'C/E', 'C/F', 'C/G', 'D/A', 'D/B', 'D/Bb', 'D/C', 'D/F#', 'E/B', 'E/C#', 'E/D', 'E/D#', 'E/F', 'E/F#', 'E/G', 'E/G#', 'Em/B', 'Em/C#', 'Em/D', 'Em/D#', 'Em/F', 'Em/F#', 'Em/G', 'Em/G#', 'F/A', 'F/C', 'F/D', 'F/D#', 'F/E', 'F/G', 'Fm/C', 'G/B', 'G/D', 'G/E', 'G/F', 'G/F#' def __init__(self): self.head = Chord(None, None) self.build_tree() def build_tree(self): potential_chords = chord_data.data for notes in PotentialChords.BASE_CHORDS: self.head.add_child(Chord(notes, None)) for child in self.head.children: for potential_chord in potential_chords: if child.chord in potential_chord['chord']: Chord(potential_chord, child) def random_chord(self): chord_family = PotentialChords.BASE_CHORDS[random.randrange(0, len(PotentialChords.BASE_CHORDS))] potential_chords = self.chords_in_family(chord_family) return potential_chords[random.randrange(0, len(potential_chords))] def random_easy_chord(self): chord_family = PotentialChords.BASE_CHORDS[random.randrange(0, len(PotentialChords.BASE_CHORDS))] potential_chords = self.find_where({'modifier': 'major'}) return potential_chords[random.randrange(0, len(potential_chords))] def chords_in_family(self, family): for note_family in self.head.children: if note_family.chord == family: return note_family.children def find_where(self, chord_options): matching_nodes = [] for note_family in self.head.children: for chord in note_family.children: if chord.matches_critera(chord_options): matching_nodes.append(chord) return matching_nodes
def show_stats(title, songs): print('=' * 32, title) chord_counter = Counter() for song in songs: for measure in song.measures: chord_counter[measure.chord.simplified()] += measure.reps for k, v in sorted(chord_counter.items(), key=lambda p: -p[1]): print("{:10} {:10} {:7.02f}% {}".format( k.to_roman_numeral(), v, *max((100 * count_chord_frac(song, k), song.name) for song in songs))) ii = Chord(2, RC.min) # (that's 2 semitones, which is coincidentally ii) IV = Chord(5, RC.maj) for percent, song_name in sorted( (100 * count_chord_frac(song, ii), song.name) for song in songs)[-100:]: print(" {:7.02f}% {}".format(percent, song_name)) for percent, song_name in sorted( (100 * count_chord_frac(song, IV), song.name) for song in songs)[-100:]: print(" {:7.02f}% {}".format(percent, song_name))
def convert(symbol: str, major_tonic: int) -> Chord: symbol = symbol.replace(' ', '') symbol = symbol.replace('+', '#') if symbol == '': return Chord(None, None) bass: Optional[int] = None seventh: Literal[None, 'min'] = None quality: Literal['maj', 'min'] = 'maj' inversions = 0 if '/' in symbol: symbol, bass_str = symbol.split('/') bass = identify_note(bass_str) def cut(s): nonlocal symbol if symbol.endswith(s): symbol = symbol[:-len(s)] return True return False if cut('7b9') or cut('7'): seventh = 'min' cut('6') if cut('m'): quality = 'min' midi = identify_note(symbol) try: if bass is not None: inversions = [ x % 12 for x in Chord(midi % 12, RelativeChord(quality, seventh)).render() ].index(bass) except ValueError: pass return Chord((midi - major_tonic) % 12, RelativeChord(quality, seventh, inversions))
def setUp(self): self.c = Note("c") self.c_sharp = Note("c#") self.d_sharp = Note("d#") self.e = Note("e") self.f = Note("f") self.f_sharp = Note("f#") self.g = Note("g") self.g_sharp = Note("g#") self.b = Note("b") self.b_flat = Note("Bb") self.c_major = Chord([self.c, self.e, self.g]) self.c_major7th = Chord([self.c, self.e, self.g, self.b]) self.c_dominant7th = Chord([self.c, self.e, self.g, self.b_flat]) self.c_altered1 = Chord([self.c, self.c_sharp, self.e, self.b_flat]) self.c_altered2 = Chord([self.c, self.d_sharp, self.e, self.b_flat]) self.c_altered3 = Chord([self.c, self.e, self.f_sharp, self.b_flat]) self.c_altered4 = Chord([self.c, self.e, self.g_sharp, self.b_flat])
def typeRelation(): df = pd.DataFrame(data[['Type 1', 'Type 2']].values) df = df.dropna() df = list(itertools.chain.from_iterable((i, i[::-1]) for i in df.values)) matrix = pd.pivot_table(pd.DataFrame(df), index=0, columns=1, aggfunc="size", fill_value=0).values.tolist() print(pd.DataFrame(matrix)) names = np.unique(df).tolist() print(pd.DataFrame(names)) Chord(matrix, names, colors=colorList).to_html()
class TestChord(TestCase): def setUp(self): self.c = Note("c") self.c_sharp = Note("c#") self.d_sharp = Note("d#") self.e = Note("e") self.f = Note("f") self.f_sharp = Note("f#") self.g = Note("g") self.g_sharp = Note("g#") self.b = Note("b") self.b_flat = Note("Bb") self.c_major = Chord([self.c, self.e, self.g]) self.c_major7th = Chord([self.c, self.e, self.g, self.b]) self.c_dominant7th = Chord([self.c, self.e, self.g, self.b_flat]) self.c_altered1 = Chord([self.c, self.c_sharp, self.e, self.b_flat]) self.c_altered2 = Chord([self.c, self.d_sharp, self.e, self.b_flat]) self.c_altered3 = Chord([self.c, self.e, self.f_sharp, self.b_flat]) self.c_altered4 = Chord([self.c, self.e, self.g_sharp, self.b_flat]) def test_qualities(self): self.assertEqual(self.c_major.qualities, ["Major 3rd", "Perfect 5th"]) def test_name(self): self.assertEqual(self.c_major.__str__(), "C Major") def test_major_chord(self): self.assertEqual(self.c_major.description, 'Major') def test_major7th_chord(self): self.assertEqual(self.c_major7th.description, "Major 7th") def test_dominant7th_chord(self): self.assertEqual(self.c_dominant7th.description, "Dominant 7th") def test_altered_chord(self): self.assertEqual(self.c_altered1.description, "Altered") self.assertEqual(self.c_altered2.description, "Altered") self.assertEqual(self.c_altered3.description, "Altered") self.assertEqual(self.c_altered4.description, "Altered")
def breed(a, b, debug=False): fingers = [] for i in range(4): if mutate(): i += 1 # Skip finger i (this means that the child will have one less finger) if i >= len(a.fingers): a_finger = None else: a_finger = a.fingers[i] if i >= len(b.fingers): b_finger = None else: b_finger = b.fingers[i] desired_finger = combine_2(a_finger, b_finger, i, debug=debug) if desired_finger is not None: fingers.append(desired_finger) c = Chord(fingers=fingers) if debug: print('Chord {} bred with Chord {}'.format(a.subplot, b.subplot)) return c
def epochs(runs, display_graphs=True, display_chords=True): max_fitnesses = [] for epoch in range(runs): print('Epoch', epoch) pop = [] fitnesses = [] for i in range(MAX_POP_SIZE): chord = Chord() pop.append(chord) #print('Beginning natural selection with {} organisms'.format(len(pop))) if NUM_STEPS!=-1: # Repeat following for x number of steps: for step in range(NUM_STEPS): plt.clf() evolution_step(step, pop, fitnesses, save_best=True, display_chords=display_chords, console_prints=False) else: step = 0 while patient(fitnesses, monitor='mean'): plt.clf() evolution_step(step, pop, fitnesses, save_best=True, display_chords=display_chords, console_prints=False) step+=1 fitnesses = np.array(fitnesses) max_fitnesses.append(pop[0].fitness) # assumption that the first chord is the lowest fitness (almost guaranteed to be true) if display_graphs: plt.figure() plt.subplot(2,1,1) plt.title('Average fitness at each step') plt.plot(np.mean(fitnesses, axis=1)) plt.subplot(2,1,2) plt.title('Minimum fitness at each step') plt.plot(np.amin(fitnesses, axis=1)) plt.show() return max_fitnesses
def one_epoch(display_graphs=True, display_chords=True): pop = [] fitnesses = [] for i in range(MAX_POP_SIZE): chord = Chord() pop.append(chord) #print('Beginning natural selection with {} organisms'.format(len(pop))) if NUM_STEPS!=-1: # Repeat following for x number of steps: for step in range(NUM_STEPS): plt.clf() evolution_step(step, pop, fitnesses, save_best=True, display_chords=display_chords, console_prints=False) else: step = 0 while patient(fitnesses, monitor='mean'): plt.clf() evolution_step(step, pop, fitnesses, save_best=True, display_chords=display_chords, console_prints=False) step+=1
def main(): print("Entering new node details...") print("Enter files directory: ") files_dir = input() if not os.path.isdir(files_dir): print("Path does not exist!") exit(1) print("Enter node ip/hostname: ", end='') ip = input() print("Enter node port: ", end='') port = int(input()) id = get_hash((ip, port)) node = Node(id, ip, port) print("\nEntering details of an existing node...") print("Enter ip/hostname (enter -1 if current node is the first node): ", end='') oldNode = None ip = input() if ip != '-1': print("Enter port: ", end='') port = int(input()) id = get_hash((ip, port)) oldNode = Node(id, ip, port) print("Joining chord network...") else: print("Populating with 100 empty files with random names...") for i in range(100): open(os.path.join(files_dir, f"{random.randint(0, 10000)}.txt"), 'a').close() print("Creating chord network...") ch = Chord(node, oldNode, files_dir) return
def plot_diagrams(self, matrices, names, l_labels): for i, (matrix, name) in enumerate(zip(matrices, names)): colors = (get_colors(gray=name, color=l_labels)) diagram = Chord( matrix, name, colors=colors, #"d3.schemeSet1", opacity=0.9, padding=0.01, width=self.width, font_size="10px", font_size_large="10px", label_color="#454545", wrap_labels=self.wrap, credit=False, margin=self.margin, ) diagram.show() diagram.to_html(f'{self.filename}_{i}.html')
def chord_creation_flow(self): fundamental_pitch = self.pick_pitch() accidental = self.pick_accidental() quality = self.pick_quality() new_chord = Chord(fundamental_pitch, accidental, quality, extra_notes=[]) if quality == 'major' or quality == "minor": optional_interval_5th_accidental = self.add_or_not() optional_th_type = self.add_or_not() optional_sus_type = self.add_or_not() optional_add_notes = self.add_or_not() if optional_interval_5th_accidental: interval_5th_accidental = self.pick_accidental() new_chord.add_interval_5th_accidental(interval_5th_accidental) if optional_th_type: th_type = self.pick_th_type() new_chord.add_pick_th_type(th_type) if optional_sus_type and not optional_th_type and not optional_interval_5th_accidental: sus_type = self.pick_sus_type() new_chord.add_pick_sus_type(sus_type) if optional_add_notes: new_chord.add_extra_note(self.pick_notes()) if self.add_or_not(): new_chord.add_bass_slash_note(self.pick_bass_slash_note()) return new_chord
from chord import Chord chords = [ Chord('A Maj', 'x02220', '213'), Chord('A7', 'x02020', '12'), Chord('A min', 'x02210', '231'), Chord('A min7', 'x02x10', '21'), Chord('A Maj7', 'x02120', '213'), Chord('Bb Maj', 'x1333x', '1234'), Chord('B7', 'x21202', '2134'), Chord('B min', 'x2443x', '1342'), Chord('C Maj', 'x32010', '321'), Chord('C7', 'x32310', '3241'), Chord('C Maj7', 'x32000', '32'), Chord('D Maj', 'xx0232', '132'), Chord('D7', 'xx0212','213'), Chord('D min', 'xx0231','231'), Chord('D min7', 'xx0222','123'), Chord('E Maj', '022100','231'), Chord('E7', '020100','21'), Chord('E min', '022000','23'), Chord('E min7', '020000','2'), Chord('F', 'xx3211','3211'), Chord('F Maj7', 'xx3210','321'), Chord('G Maj', '320003','213'), Chord('G7', '320001', '321') ]
node = np.unique(node) # 显示连接网络 weight_filter = weight[id_mat[0], id_mat[1]] wei_node = np.hstack([node1, node2]).T wei_node = np.vstack([wei_node, np.hstack([weight_filter, weight_filter])]).T nodes = [{"name": nd, "symbolSize": np.sum(np.abs(np.float64(wei_node[:,1][np.in1d(wei_node[:,0], str(nd))])))*10} for nd in node] links = [{"source": str(nd1), "target": str(nd2)} for (nd1, nd2) in zip(node1, node2)] graph= ( Graph() .add("", nodes,links, repulsion=1000) .set_global_opts(title_opts=opts.TitleOpts(title="前0.1%的权重")) ) graph.render() # 只显示靠前的权重 plt.imshow(weight, cmap="RdBu_r") plt.colorbar() plotting.plot_connectome(weight, node_coords, annotate=True) view = plotting.view_connectome(weight, node_coords) view.open_in_browser() from chord import Chord names = [str(i) for i in range(246)] chrod_fig = Chord(weight, names, colors="d3.schemeSet2").to_html("chrod_fig.html")
import chord_pb2 as cp import grpc import chord_pb2_grpc as cpg from concurrent import futures import sys import time from chord import Chord import json import grpc if __name__ == '__main__': port = int(sys.argv[1]) t = sys.argv[2] config = json.load(open('config.json', 'r')) c = Chord(port, config) server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) if t == 'join': print('join to ', config['master']) c.Join(config['master']) cpg.add_chordServicer_to_server(c, server) server.add_insecure_port(f'[::]:{port}') server.start() try: while True: time.sleep(60 * 60 * 24) except KeyboardInterrupt: server.stop(0)
from note_dict import note_dict from chord import Chord import numpy as np from optimitzation import Optimization import time bases = [] bases_chords = [] c = Chord() o = Optimization() print("Introduce your inputs: (Write return to delete previous note)") print(" (Write exit to finish)") print("") # Listen for the inputs while True: base = input("") if base == "exit": break if base == "return": if not bases: print("No previous inputs found") else: bases.pop() print("Current inputs:", bases) continue if base in note_dict: bases.append(note_dict[base]) else: print("Not recognized")
import sys from chord import Chord from fingerboard import Fingerboard args = sys.argv chordName = args[1] if len(args) > 2: tensions = args[2:] tones = Chord.parse(chordName, tensions) inv = {v: k for k, v in tones.items()} print "" print "%s %s" % (chordName, " ".join(tensions)) print "" for key in sorted(inv.keys()): print " %3s: %2s" % (key, inv[key]) Fingerboard.dump(tones)
import sys from chord import Chord from fingerboard import Fingerboard args = sys.argv chordName = args[1] if len(args) > 2: tensions = args[2:] tones = Chord.parse(chordName, tensions) inv = {v:k for k, v in tones.items()} print "" print "%s %s" % (chordName, " ".join(tensions)) print "" for key in sorted(inv.keys()): print " %3s: %2s" % (key, inv[key]) Fingerboard.dump(tones)
class Instrument(): """ Class which generates sounds from numerical frequency values. """ def __init__(self, tuning_type='equal', initial_duration=1, initial_root_tonality_frequency=440): self.duration = initial_duration self.set_root_tonality_frequency(initial_root_tonality_frequency) self.scale = Scale().get_ratios(tuning_type) intervals = [0 for i in range(5)] self.synths = [ self.synthesize(freq=(self.root_tonality_frequency * interval)) for interval in intervals ] self.set_envelope(self.duration) self.chord_generator = Chord(self.scale, self.root_tonality_frequency) def out(self): mix = Mix(self.synths, voices=2, mul=0.7, add=0) disto = Disto(mix, drive=0.01, slope=0.7, mul=self.envelope, add=0) verb = WGVerb(disto, feedback=0.5, cutoff=5000, bal=0.55, mul=1, add=0) return verb def set_root_tonality_frequency(self, frequency): self.root_tonality_frequency = frequency def get_root_tonality_frequency(self): return self.root_tonality_frequency def set_chord(self, chord_name='maj', scale_position=0): self.chord_generator.set_root_frequency(self.scale[scale_position] * self.root_tonality_frequency) freqs = self.chord_generator.get_chord_frequencies(chord_name) number_of_frequencies_in_chord = len(freqs) for x in range(5): if ((x + 1) <= number_of_frequencies_in_chord): self.synths[x].setFreq(freqs[x]) else: self.synths[x].setFreq(0) def play(self, duration): self.set_envelope_duration(duration) self.envelope.play() def set_envelope_duration(self, duration): if (self.duration == duration): return d = duration self.envelope.setDur(d) self.envelope.setAttack(d * .05) self.envelope.setDecay(d * .25) self.envelope.setSustain(d * .6) self.envelope.setRelease(d * .1) def set_envelope(self, duration): d = duration self.envelope = Adsr(attack=d * .05, decay=d * .25, sustain=d * .6, release=d * .1, dur=d, mul=.5) def play_chord(self, chord_name, duration): #self.synths = self.envelope.setDur(duration) self.envelope.play() def synthesize(self, freq): return Sine(freq=[freq * n for n in range(1, 8)], mul=[0.39, 0.55, 0.65, 0.5, 0.15, 0.09, 0.05, 0.02])
duration = 1 # in beats volume = 100 # 0 - 127 ############################## ####### Test Settings ######## # output_filename = '' MyMIDI = MIDIFile( 2 ) # One track, defaults to format 1 (tempo track is created automatically) MyMIDI.addTempo(track, time, tempo) MyMIDI.addTrackName(0, time, 'Test Track 0') MyMIDI.addTrackName(1, time, 'Test Track 1') # A_Maj_Chord = Chord.chord_major(Chord.ROOT_A, 'A Major', 2, 1) A_Maj_Chord = Chord.get_chord_major(None, Chord.ROOT_A) # Chord.print_notes(A_Maj_Chord, print_notes_detailed) A_Maj_Chord.duration = 2 A_Maj_Chord.time = 1 key_Bb_major = Key('Bb', 'Major', 58) key_Cs_minor = Key('Cs', 'Minor', 49) ## Riffs riff_Bb_major = MelodicRiff(key_Bb_major) riff_Bb_major.create_riff(16) riff_Bb_major2 = MelodicRiff(key_Bb_major, [], 1) riff_Bb_major2.create_riff(16) riff_Cs_minor = MelodicRiff(key_Cs_minor, [], 1) riff_Cs_minor.create_riff(16)
from chord import Chord matrix = [[] * 51] names = [ 'G_maj', 'D_maj_min7', 'E_min', 'B_maj_min7', 'A_maj_min7', 'D_maj', 'G_maj_maj7', 'Eb_dim', 'B_min_min7', 'G_min', 'C_min', 'F_maj', 'Bb_maj_maj7', 'C_min_min7', 'Bb_maj', 'G_maj_min7', 'G_min_min7', 'Eb_maj_maj7', 'E_maj', 'E_maj_maj7', 'Eb_maj_min7', 'Ab_maj', 'Ab_maj_maj7', 'C_maj_min7', 'F_min', 'Ab_maj_min7', 'C#_maj', 'F_maj_min7', 'Bb_min_min7', 'F#_maj', 'Bb_dim_dim7', 'A_dim_min7', 'Bb_dim', 'F_maj_maj7', 'G_dim', 'F#_dim_min7', 'E_dim_min7', 'A_min_min7', 'C#_min_min7', 'D_dim', 'A_maj_maj7', 'Ab_dim', 'Bb_min', 'F_min_min7', 'C#_dim', 'C_maj', 'D_maj_maj7', 'A_dim_dim7', 'B_dim_dim7', 'Eb_maj', 'B_maj' ] Chord(matrix, names).to_html()
def __init__(self): self.head = Chord(None, None) self.build_tree()
aggfunc="size", fill_value=0).values.tolist() #Creating a matrix names = np.unique(genres).tolist() #taking a list of unique genres colors = [ "#e6194B", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#42d4f4", "#f032e6", "#bfef45", "#fabebe", "#469990", "#e6beff", "#9A6324", "#fffac8", "#800000", "#aaffc3", "#a9a9a9", "#ffd8b1", "#000075", "#a9a9a9", ] Chord(matrix, names, colors=colors, wrap_labels=False, margin=50).to_html() #output
def initialFullSizeGraph(request): #import pandas as pd df_dataset = pd.read_csv(request.FILES['csv_data'] graph_json = makeGraph(request, df_dataset) startYear = df_dataset["date"].min() endYear = df_dataset["date"].max() return JsonResponse({ 'graph': graph_json, 'parameters': { 'timeSlider': { 'startYear': 1998, 'startMonth': 11, 'endYear': 2002, 'endMonth': 6 } } }) def chordDiagram(request): import numpy as np #import pandas as pd from chord import Chord df_enron = filterDataByTime(request ,pd.read_csv(request.FILES['csv_data'])) names = ['Managing Director', 'In House Lawyer', 'Vice President', 'Employee', 'Unknown', 'Manager', 'Director', 'Trader', 'CEO', 'President'] df_chord = df_enron.groupby(['fromJobtitle', 'toJobtitle'])['date'].count() df_chord = df_chord.unstack().fillna(0).astype(int) df_chord = df_chord.reindex(names) df_chord = df_chord[names] matrix = df_chord.values.tolist() print(Chord(matrix, names, wrap_labels=False)) return HttpResponse(Chord(matrix, names, wrap_labels=False).to_html()) def individualInfo(request): #import pandas as pd import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [10, 5] # default hor./vert. size of plots, in inches plt.rcParams['lines.markeredgewidth'] = 1 # to fix issue with seaborn box plots; needed after import seaborn # reveal a hint only while holding the mouse down from IPython.display import HTML HTML("<style>.h,.c{display:none}.t{color:#296eaa}.t:active+.h{display:block;}</style>") # hide FutureWarnings, which may show for Seaborn calls in most recent Anaconda import warnings warnings.filterwarnings("ignore", category=FutureWarning) df_enron = pd.read_csv(request.FILES['csv_data']) Person_ID_1, ID_mail, job_title, mails_send, mean_sentiment_send, min_sentiment_send, max_sentiment_send, mails_received, mean_sentiment_received, min_sentiment_received, max_sentiment_received, array_mails_sent, array_mails_received = getIndividualInfoInner(df_enron, int(request.POST['person_id'])) df_enron_tf = filterDataByTime(request,df_enron) Person_ID_1_tf, ID_mail_tf, job_title_tf, mails_send_tf, mean_sentiment_send_tf, min_sentiment_send_tf, max_sentiment_send_tf, mails_received_tf, mean_sentiment_received_tf, min_sentiment_received_tf, max_sentiment_received_tf, array_mails_sent_tf, array_mails_received_tf = getIndividualInfoInner(df_enron_tf, int(request.POST['person_id'])) #Person_ID_1, ID_mail, job_title, mails_send, mean_sentiment_send, min_sentiment_send, max_sentiment_send, mails_received, mean_sentiment_received, min_sentiment_received, max_sentiment_received return JsonResponse({ 'meta': { 'person_id': str(Person_ID_1), 'mail_address': str(ID_mail), 'job_title': str(job_title), }, 'all_time': { 'mails_sent': str(mails_send), 'min_sentiment_sent': str(min_sentiment_send), 'mean_sentiment_sent': str(mean_sentiment_send), 'max_sentiment_sent': str(max_sentiment_send), 'array_mails_sent': array_mails_sent, 'mails_received': str(mails_received), 'min_sentiment_received': str(min_sentiment_received), 'mean_sentiment_received': str(mean_sentiment_received), 'max_sentiment_received': str(max_sentiment_received), 'array_mails_received': array_mails_received, }, 'time_filtered': { 'mails_sent': str(mails_send_tf), 'min_sentiment_sent': str(min_sentiment_send_tf), 'mean_sentiment_sent': str(mean_sentiment_send_tf), 'max_sentiment_sent': str(max_sentiment_send_tf), 'array_mails_sent': array_mails_sent_tf, 'mails_received': str(mails_received_tf), 'min_sentiment_received': str(min_sentiment_received_tf), 'mean_sentiment_received': str(mean_sentiment_received_tf), 'max_sentiment_received': str(max_sentiment_received_tf), 'array_mails_received': array_mails_received_tf, } }) def getIndividualInfoInner(df_enron, person_id): Person_ID_1 = person_id person_send = df_enron['fromId'] == Person_ID_1 person_received = df_enron['toId'] == Person_ID_1 df_1 = df_enron[person_send] df_2 = df_1[['fromEmail']] df_3 = df_2.describe() ID_mail = df_3['fromEmail']['top'] df_describe_person = df_1[['fromJobtitle']].describe() job_title = df_describe_person['fromJobtitle']['top'] mails_send = df_1['sentiment'].count() mean_sentiment_send = df_1['sentiment'].mean() min_sentiment_send = df_1['sentiment'].min() max_sentiment_send = df_1['sentiment'].max() df_received = df_enron[person_received] mails_received = df_received['sentiment'].count() mean_sentiment_received = df_received['sentiment'].mean() min_sentiment_received = df_received['sentiment'].min() max_sentiment_received = df_received['sentiment'].max() emails_sent = 'none' try: df_emails_sent_1 = df_1.groupby('toId').describe() df_emails_sent_2 = df_emails_sent_1['fromId'] emails_sent = df_emails_sent_2[['count']].to_json() except: pass emails_received = 'none' try: emails_received_1 = df_received.groupby('fromId').describe() emails_received_2 = emails_received_1['toId'] emails_received = emails_received_2[['count']].to_json() except: pass return Person_ID_1, ID_mail, job_title, mails_send, mean_sentiment_send, min_sentiment_send, max_sentiment_send, mails_received, mean_sentiment_received, min_sentiment_received, max_sentiment_received, emails_sent, emails_received
for i in range(len(characters)): for j in range(i + 1, len(characters)): pairings.append([characters[i], characters[j]]) people.add(characters[i]) people.add(characters[j]) people = list(people) m = [[0 for i in range(len(people))] for j in range(len(people))] for pair in pairings: i = people.index(pair[0]) j = people.index(pair[1]) m[i][j] = m[i][j] + 1 m[j][i] = m[j][i] + 1 for x in range(len(m)): temp = [0 if a_ < 2000 else a_ for a_ in m[x]] m[x] = temp filter_m = [] filter_people = [] delete_index = [] for index, i in enumerate(m): if any(v > 0 for v in i): filter_m.append(i) filter_people.append(people[index]) elif all(v == 0 for v in i): delete_index.append(index) for index in sorted(delete_index, reverse=True): for i in filter_m: del i[index] Chord(filter_m, filter_people, width=2000).to_html()